Conditionals
Programming Languages · Python Control Flow & Lists · 12 min
Let your program make decisions with if, elif and else.
True or False?
A comparison asks a yes or no question. Python answers with True or False.
print(5 > 3) # True
print(5 == 3) # False
The comparisons are == (equal), != (not equal), <, >, <= and >=. Careful: = stores a value, == compares.
Print whether
ageis 13 or more (age >= 13).Print whether
ageequals 18.
if
if runs some code only when a condition is True. End the line with a colon : and indent the code underneath by 4 spaces. The indented lines belong to the if.
if 10 > 5:
print("Yes!")
Write an
ifthat printsIt's hotwhentempis more than 25.
else
else is the backup plan: it runs when the if condition is False. It lines up with the if and has its own colon.
if raining:
print("Take an umbrella")
else:
print("Enjoy the sun")
Print
It's hotiftempis more than 25,elseprintIt's not hot.
elif
Need more than two choices? Add elif (short for "else if"). Python checks each condition from the top and runs only the first one that's True.
if speed > 100:
print("Too fast")
elif speed > 50:
print("Fine")
else:
print("Slow")
Print
Aifscoreis 90 or more,Bif it's 70 or more, otherwiseC.
and, or, not
Combine conditions with three little words:
and: both must beTrueor: at least one must beTruenot: flipsTruetoFalseand back
if hungry and has_snack:
print("Snack time")
Print
Come inifageis 18 or moreandhas_ticketis True.Print
not has_ticket.
Put it together: ticket prices
A cinema charges by age: under 12 pays 5, 65 or over pays 6, everyone else pays 10. Pick the right price with if, elif and else, then print it.
Use
if,elifandelseto setpriceto 5, 6 or 10.Print
Ticket: 6usingprice.