Learn Python · lesson 15 of 60 · about 7 minutes
Combining Conditions
Remind Sam about the umbrella: use and/or inside if statements, and pick a value in one line with x if condition else y.
What you'll learn
- Use and/or in if statements
- Write a conditional expression
- Keep conditions readable
Umbrella or not?
Sam also wants a reminder about the umbrella. It's one of two messages, and a whole if and else just to choose a bit of text feels long. Python can pick a value in one line.
Logic inside if
The and, or and not you learned work directly in an if statement. Often one combined condition replaces a nested if.
One condition instead of two ifs
day = "Saturday"
homework_done = True
if (day == "Saturday" or day == "Sunday") and homework_done:
print("Game time!")
else:
print("Not yet.")Output
Game time!Choosing a value in one line
When you just need to pick between two values, write a if condition else b. It's called a conditional expression.
A one-line choice
lives = 0
status = "Game over" if lives == 0 else "Playing"
print(status)
print("even" if 10 % 2 == 0 else "odd")Output
Game over
evenThe umbrella reminder
rain = input("Rain today? ").strip().lower() == "yes"
print("Take an umbrella" if rain else "No umbrella needed")Output
Rain today? Take an umbrellaTip
Brackets make mixed and/or conditions clear. (a or b) and c is easier to trust than a or b and c.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.