LESSON 09
Making Decisions
Until now, your program ran every line, every time. Now it chooses.
USES: variables, comparisons and True/False (Lesson 8), input( ) and int( ) (Lessons 6 and 7), .lower( ) (Lesson 4).
01
The bouncer gets a job
In Lesson 8 your bouncer learned to ask 'are you 18 or older?' and answer True or False. But the bouncer never did anything with the answer. This lesson fixes that. Read it like English: if age is at least 18, then print "Welcome in".
BLUEPRINT ยท TAP OR HOVER EACH PIECE
Blueprint 1 of 1: the anatomy of an if. Tap each piece, including the empty gap at the start of the second line.
02
When the answer is False
What if the person is too young? The condition is False, so the indented line is skipped. But print("Done") has no indentation, so it does not belong to the if. It runs every time.
03
else, the other path
Often you want one thing when the answer is True and something else when it is False. That is else. Exactly one of the two paths runs, never both and never neither.
04
elif, more than two paths
Sometimes two paths are not enough. elif is short for 'else if'. Python checks the conditions from the top, one at a time. The first one that is True runs, and then Python skips the rest.
05
Order matters, because the first match wins
What if the easy condition comes first? A score of 95 should be an A, but 95 >= 70 is True, so Python stops at the first branch and prints C. Put the strictest condition first.
06
Decisions with input
Now combine it with everything from earlier lessons. Notice the int( ): this is the trap from Lessons 7 and 8. input( ) gives text, and text is never equal to or greater than a number. Convert first, then compare.
07
Decisions with text
Text works too, and it is where .lower( ) earns its place. Without it, "YES" == "yes" is False, because Python is case-sensitive (Lesson 8). Lowercasing the answer first means every spelling of yes works.
08
Reading error messages
Three mistakes show up constantly, so here they are on purpose. Missing indentation gives an IndentationError: expected an indented block. A missing colon gives SyntaxError: expected ':'. One = instead of two gives a SyntaxError in which Python even guesses you meant ==. None of these mean you are doing badly. Python is pointing at the exact spot: read the message, look at the line it names, fix it.
09
Quick quiz: which branch runs?
temp = 30 if temp > 25: print("Hot") elif temp > 15: print("Nice") else: print("Cold") What prints?
10
Quick quiz: one if or two?
x = 5 if x > 3: print("A") if x > 4: print("B") else: print("C") What prints?
11
Quick quiz: which line always runs?
n = 3 if n > 5: print("big") print("end") Which line always runs?