When an if/else is only used to choose between two values, Python lets you write it on a single line. It is called the conditional (or ternary) operator.
Syntax
value = result_if_true if condition else result_if_false
It reads almost like an English sentence. Example:
age = int(input())
status = "adult" if age >= 18 else "minor"
print(status)
It is equivalent to:
if age >= 18:
status = "adult"
else:
status = "minor"
Inside a print
It is very handy to show one message or another without an intermediate variable:
n = int(input())
print("even" if n % 2 == 0 else "odd")
Classic example: the larger of two
a = int(input())
b = int(input())
print(a if a > b else b) # same as max(a, b)
Chaining conditions
You can chain another conditional operator in the else part, but it quickly becomes hard to read:
a = int(input())
b = int(input())
print("greater" if a > b else "smaller" if a < b else "equal")
If you have more than two cases, a regular if/elif/else is usually clearer.
When to use it
- Use it to choose between two values or two short texts.
- Do not use it if each branch needs several statements: use a regular
ifthere. - Both sides must be expressions (values), not statements such as a
print()followed by another line.
Practice with Conditional operator.