Python Conditional Expressions
A conditional expression is a one-line form that picks one of two values. The condition sits in the middle of the line.
Pick a value in one line
The condition sits in the middle of the line.
age = 20
label = "adult" if age >= 18 else "child"
print(label)Another quick choice
The line reads almost like a sentence.
rain = True
item = "umbrella" if rain else "sunglasses"
print(item)The same choice with if and else
This longer form does the same job as the first snippet. The one-line form just says it faster.
if age >= 18:
label = "adult"
else:
label = "child"Example
number = 7
parity = "even" if number % 2 == 0 else "odd"
print(number, "is", parity)
temperature = 24
feeling = "warm" if temperature >= 20 else "cold"
print("It feels", feeling)Key points
- Form: value_if_true if condition else value_if_false.
- A conditional expression picks one value in a single line.
- Read it from the middle.
- Test the condition, then pick the matching side.
- Use it to choose a value for a variable.
- It does not run blocks of code.
- Keep it short.
- If the line needs a second read, use a normal if and else instead.
In this example, number is 7. The test 7 % 2 == 0 is false, because 7 leaves a remainder of 1. So parity picks the else side, "odd". Next, temperature is 24. The test 24 >= 20 is true, so feeling picks "warm". The print lines then show both labels. You will use this trick more later.
Note
and and or can also hand back values, not just True or False.
The line name or "Guest" gives the name, or "Guest" when the name is empty.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
score = 60 and label = "high" if score > 80 else "low". What is label?