A Ternary Operator in Python is a one-line conditional expression that allows you to assign a value based on a condition — similar to the if-else statement but in a compact form.
It is often used to make code shorter and more readable for simple conditional assignments.
🔹 Syntax:
value_if_true if condition else value_if_false- If the condition is
True, the expression returnsvalue_if_true. - Otherwise, it returns
value_if_false.
🧩 Example 1: Basic Usage
a = 10
b = 20
max_num = a if a > b else b
print("Maximum:", max_num)Output:
Maximum: 20🧩 Example 2: Checking Even or Odd
num = 7
result = "Even" if num % 2 == 0 else "Odd"
print(result)Output:
Odd🧩 Example 3: Nested Ternary Operator
a = 5
b = 10
c = 3
largest = a if (a > b and a > c) else (b if b > c else c)
print("Largest number:", largest)Output:
Largest number: 10🧩 Example 4: Inline Conditional Printing
age = 18
print("Eligible" if age >= 18 else "Not Eligible")Output:
Eligible🧩 Example 5: Using Ternary Operator with Functions
def check_temperature(temp):
return "Hot" if temp > 30 else "Cold"
print(check_temperature(35))
print(check_temperature(20))Output:
Hot
Cold🔹 In Summary
- The ternary operator provides a shorter alternative to traditional
if-elsestatements. - Syntax:
value_if_true if condition else value_if_false - Best used for simple conditional assignments to keep code concise and readable.
