0
0
Pythonprogramming~5 mins

Ternary conditional expression in Python

Choose your learning style9 modes available
Introduction
A ternary conditional expression lets you choose between two values in one simple line, like picking between two options quickly.
When you want to set a value based on a quick yes/no question.
When you want to write shorter code instead of using multiple lines with if and else.
When you want to decide what to show or do based on a simple condition.
When you want to assign a default value if something is missing or false.
When you want to make your code easier to read by avoiding long if-else blocks.
Syntax
Python
value_if_true if condition else value_if_false
The condition is checked first; if it is true, the first value is used.
If the condition is false, the second value is used instead.
Examples
Sets 'status' to 'Adult' if age is 18 or more, otherwise 'Minor'.
Python
age = 20
status = "Adult" if age >= 18 else "Minor"
Chooses 'Pass' or 'Fail' based on the score.
Python
score = 85
result = "Pass" if score >= 50 else "Fail"
Decides what message to show depending on the weather.
Python
is_raining = False
message = "Take umbrella" if is_raining else "No umbrella needed"
Sample Program
This program checks if the temperature is above 25. If yes, it says 'Hot', otherwise 'Cold'. Then it prints the result.
Python
temperature = 30
weather = "Hot" if temperature > 25 else "Cold"
print(f"The weather is {weather}.")
OutputSuccess
Important Notes
Ternary expressions are great for simple choices but avoid using them for complex conditions to keep code clear.
You can nest ternary expressions, but it can make the code hard to read.
Remember the order: first the value if true, then 'if', then the condition, then 'else', then the value if false.
Summary
Ternary conditional expressions let you pick between two values in one line.
They make simple decisions easy and your code shorter.
Use them for quick yes/no choices to keep your code clean and readable.