Else and the three questions
An if ... else statement gives two paths. Lines indented under else: run in every other case. The word else has no condition, and it ends with a colon too. It is written at the same level as the if it belongs to, and its lines are indented. Before typing, plan the statement in three steps. Step one: what is the input and what is stored? Step two: what is the condition? Step three: what happens when it is true, and what happens when it is false? Python checks the rules before it runs anything. A missing colon or a missing indent is a syntax error, so the program does not start. A mistake like that is different from a logic error, where the program runs but gives the wrong answer.
| Step | Question | Answer for the battery program |
|---|---|---|
| 1 | What is the input? | percent, a whole number |
| 2 | What is the condition? | percent < 20 |
| 3 | True: what happens? False: what happens? | print Charge soon; print Battery fine |
1percent = int(input("Battery? ")) 2if percent < 20: 3 print("Charge soon") 4else: 5 print("Battery fine")
Charge soon
1percent = int(input("Battery? ")) 2if percent < 20: 3 print("Charge soon") 4print("Checked")
Charge soon Checked
| Mistake | Last line of the message |
|---|---|
| colon missing after the condition | SyntaxError: expected ':' |
| print not indented | IndentationError: expected an indented block after 'if' statement on line 2 |
Three-question planner (no computer). Choose a situation, such as ‘a school gate bell rings if it is after 8 o’clock’ or ‘a pet needs food if its bowl is nearly empty’. Draw a table with the three questions: input, condition, and what happens when true and when false. Fill it in. Write the if ... else program on paper, with colons and indentation. Ask a partner to find one deliberate mistake that you add (a missing colon or indent). Swap roles. If you have a computer or tablet, type a program with and without the mistake and read the last line of the message.
1INPUT kg 2IF kg > 20 THEN 3 OUTPUT "Extra bag fee" 4ELSE 5 OUTPUT "No fee" 6ENDIF
1age = int(input("Age? ")) 2if age >= 12 3 print("Teen")
1age = int(input("Age? ")) 2if age >= 12: 3print("Teen")
1speed = int(input("Speed? ")) 2if speed > 50: 3 print("Slow down") 4else: 5 print("Safe speed")