The elif ladder
Python has no ELSEIF. It has elif, which is one word, followed by a condition and a colon. A chain starts with if, has any number of elif parts and may end with else. Python tests the conditions from the top. The first true condition runs its indented lines, and then Python skips the rest of the chain. This means the order of the conditions matters, just as it did in pseudocode. If the order is wrong the program still runs, but it gives wrong answers, which is a logic error. In Python, print with a comma between items puts a space between them, so print("Fare:", fare) shows Fare: 4. In our pseudocode the comma added no space.
| Pseudocode | Python |
|---|---|
| IF km <= 3 THEN | if km <= 3: |
| ELSEIF km <= 10 THEN | elif km <= 10: |
| ELSE | else: |
| ENDIF | (nothing) |
| km typed | Fare printed |
|---|---|
| 2 | Fare: 4 |
| 3 | Fare: 4 |
| 4 | Fare: 9 |
| 10 | Fare: 9 |
| 26 | Fare: 30 |
1km = int(input("Distance in km? ")) 2if km <= 3: 3 fare = 4 4elif km <= 10: 5 fare = 9 6elif km <= 25: 7 fare = 18 8else: 9 fare = 30 10print("Fare:", fare)
Fare: 9
1km = int(input("Distance in km? ")) 2if km <= 25: 3 fare = 18 4elif km <= 10: 5 fare = 9 6elif km <= 3: 7 fare = 4 8else: 9 fare = 30 10print("Fare:", fare)
Fare: 18
Ladder of cards (no computer). Draw four rungs on a large sheet. Write on each rung one condition from the taxi program, with the last rung as else. Use a counter to climb: it starts on the first rung and moves down only when the rung’s condition is false. A partner calls a distance (2, 3, 4, 10, 25 and 26). Write the fare where the counter stops. Then swap the first two rungs and call 2 again. What changed? If you have a computer or tablet, ask an adult to run both versions of the program.
1stars = int(input("Stars? ")) 2if stars >= 4: 3 print("Great") 4elif stars >= 2: 5 print("Okay") 6else: 7 print("Poor")
1INPUT sold 2IF sold >= 100 THEN 3 OUTPUT "Sold out" 4ELSEIF sold >= 50 THEN 5 OUTPUT "Selling well" 6ELSE 7 OUTPUT "Slow" 8ENDIF
1n = int(input("Number? ")) 2if n >= 10: 3 print("Medium") 4elif n >= 20: 5 print("Big") 6else: 7 print("Small")