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 age is 13 or more (age >= 13).

  • Print whether age equals 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 if that prints It's hot when temp is 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 hot if temp is more than 25, else print It'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 A if score is 90 or more, B if it's 70 or more, otherwise C.

and, or, not

Combine conditions with three little words:

  • and: both must be True
  • or: at least one must be True
  • not: flips True to False and back
if hungry and has_snack:
    print("Snack time")
  • Print Come in if age is 18 or more and has_ticket is 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, elif and else to set price to 5, 6 or 10.

  • Print Ticket: 6 using price.

More in Python Control Flow & Lists

Previous: Strings · Next: Lists