Ternary Operator in Python

Python Ternary Operator – Complete Explanation

The ternary operator in Python is used to evaluate conditions in a single line. It is the compact form of an if–else statement and is useful when solving small condition-based expressions.


✨ Syntax of Ternary Operator

variable = true_statement if condition else false_statement

# Example
print(a if condition else b)

📌 Example 1: Greater Number Check

Solution 1 (Storing result in variable)

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

res = "a is greater" if a > b else "b is greater"
print(res)

Solution 2 (Direct printing)

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

print(a if a > b else b)

📌 Example 2: Check Vowel or Consonant

s = input("Enter a character: ")

o = "Vowel" if s in ('a','e','i','o','u') else "Consonant"
print(o)

🔁 Nested Ternary Operator

Python allows multiple ternary expressions inside one another. This is called a nested ternary operator.

Syntax:

var = (true1 if condition1 else false1) if condition2 else (true2 if condition3 else false2)

📌 Example: Greatest Among Three Numbers

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

res = "a is greatest" if a > c else \
      "c is greatest" if a > b else \
      "b is greatest" if b > c else "c is greatest"

print(res)

✔ Advantages of Ternary Operator

  • Makes code shorter and cleaner
  • Provides better performance for small conditional checks

✘ Disadvantages

  • Not suitable for complex conditions
  • Nested ternary operators can reduce readability

📝 Assignments – Ternary Operator Programs

1️⃣ Check Leap Year

year = int(input("Enter year: "))

s = "Leap year" if (year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)) else "NOT Leap year"
print(s)

2️⃣ Check if a Number is Divisible by 3 and 5

num = int(input("Enter number: "))

s = "Divisible" if num % 3 == 0 and num % 5 == 0 else "Not Divisible"
print(s)

3️⃣ Check Divisibility (3, 5, Both or None)

num = int(input("Enter number: "))

s = "Divisible by 3 and 5" if num % 3 == 0 and num % 5 == 0 else \
    "Divisible by 3" if num % 3 == 0 else \
    "Divisible by 5" if num % 5 == 0 else \
    "Not divisible by 3 or 5"

print(s)

4️⃣ Check Taxable Salary

sal = int(input("Enter salary: "))

s = "Not taxable" if sal <= 250000 else \
    "Tax amount is " + str(sal - 250000)

print(s)

5️⃣ Electricity Bill Using Ternary Operator

up = float(input("Enter unit price: "))
con = float(input("Enter consumption: "))

total = up * con

s = "Pay only 100 Rs" if total < 400 else \
    "Actual bill is " + str(total) + " | Payable bill is " + str(total / 2)

print(s)