Python Programming I
Senior 4 · ICT
Python Programming I
Lesson 3 of 5
25 min
A farmers' group growing tomatoes near Rwamagana uses a sensor that measures soil moisture. The pump should start when the soil is dry, but not in the hottest hours, when much of the water would evaporate before it reached the roots. That is two decisions, one inside the other. In Unit 3 you wrote decisions as IF…THEN…ELSE in pseudocode; in this lesson you write them in Python, where the layout of the code, its indentation, is part of the language. (The thresholds in this lesson are illustrative.)
Definition
Boolean expression: an expression whose value is True or False, such as mark >= 50.
Block: a group of statements that belong together, such as the steps to run when a condition is true. In Python a block is marked by indenting its lines by the same amount, normally 4 spaces, after a line ending in a colon.
if / elif / else: Python's selection statements. elif ("else if") adds another condition to test; else catches every case not caught before.
| Python | Meaning | Example | Value |
|---|---|---|---|
== | equal to | 5 == 5.0 | True |
!= | not equal to | "Kigali" != "kigali" | True (case matters) |
< > | less than, greater than | 49 > 50 | False |
<= >= | at most, at least | 50 >= 50 | True |
and | both true | (3 > 1) and (2 > 5) | False |
or | at least one true | (3 > 1) or (2 > 5) | True |
not | reverses | not (3 > 1) | False |
Python also allows chained comparisons, as in maths: 0 <= mark <= 100 means 0 <= mark and mark <= 100.
Three rules: the if line ends with a colon; the lines of the block are indented by the same amount (PEP 8 recommends 4 spaces); the block ends where the indentation returns to the left. There is no ENDIF: the indentation does its job.
Press Run and try 72, then run again with 50 and with 49. "Result recorded" prints every time, because it is outside both blocks.
The grade algorithm from Unit 3 becomes an if … elif … else chain. Python tests the conditions from the top and runs the block of the first one that is True; the rest are skipped. A validity check comes first, so impossible marks never reach the grading.
Test it with boundary data: 80, 79, 50, 49, 100, 0, and with erroneous data: 101 and −5. Each must print what the table in Unit 3, lesson 4 predicts, and the invalid ones must print "Invalid mark". (The grade bands are illustrative.)
Worked example 1: trace the chain
| mark | not 0 ≤ mark ≤ 100 | ≥ 80 | ≥ 70 | ≥ 60 | ≥ 50 | Output |
|---|---|---|---|---|---|---|
| 67 | False | False | False | True | (skipped) | Grade C |
| 80 | False | True | (skipped) | (skipped) | (skipped) | Grade A |
| 101 | True | (skipped) | (skipped) | (skipped) | (skipped) | Invalid mark |
Every row stops at its first True. That is why 101 never reaches "Grade A", and why the order of the elif lines matters.
An if can sit inside another if's block. Each level is indented 4 more spaces. Here the pump question about the time is asked only when the soil is dry.
Try moisture 25 at hour 18 (Pump ON), 25 at hour 13 (wait), and 45 at any hour (pump OFF). The inner if/else is indented 8 spaces in total: 4 for being inside the outer if, and 4 more for its own blocks.
Worked example 2: nesting or and?
The decision "Pump ON" needs two things: dry soil and not the hottest hours. With logical operators it fits in one condition:
if moisture < 30 and not (11 <= hour <= 15):
print("Pump ON")This is shorter, but it says nothing in the other cases. The nested version gives a different, helpful message for each situation (dry but too hot; moist enough). Choose nesting when each branch needs its own action, and and/or when you only need to know whether all the conditions hold.
Press Run: Python stops with IndentationError: expected an indented block. The print must be indented under the if. Indent it 4 spaces and run again. A related mistake, if mark = 50:, gives a SyntaxError, because = assigns and == compares.
Corey Schafer: Python Tutorial for Beginners 6, Conditionals and Booleans: If, Else and Elif Statements. Watch how comparisons, and, or and not are combined in if statements, and which values Python treats as False.
Warning
= is not ==. if mark == 50: compares; if mark = 50: is a SyntaxError.
Mix neither tabs and spaces nor different widths. All lines of a block must have exactly the same indentation. IDLE inserts 4 spaces when you press Tab, which is safest.
Strings compare exactly. "yes" == "Yes" is False. When checking a typed answer, compare answer.lower() == "yes".
Tip
Test every branch. A chain with five branches needs at least five test values, one for each, plus the boundaries between them. A branch never tested is a branch that may hide a bug.
Practice
7 == 7.0; (b) "A" != "a"; (c) not (4 < 2); (d) (5 > 2) and (3 == 4); (e) 1 <= 0 <= 5.%.)if with and/or, and test it with 1900, 2000, 2024 and 2026.if age > 18 on one line and print("Adult") on the next, not indented.moisture = 30 and hour = 9 in the pump program? Explain why, and say whether the boundary seems sensible.elif mark >= 50 first and elif mark >= 80 last. Evaluate the program with the marks 85 and 45.n = int(input("Number: ")); if n % 2 == 0: print("even"); else: print("odd") (each print indented on its own line).t = float(input("Temperature: ")); if t < 15: print("Cold"); elif t <= 25: print("Warm"); else: print("Hot").if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: leap, else: not. 1900 not leap; 2000 leap; 2024 leap; 2026 not leap.if age < 5: fare = 0; elif age <= 12: fare = 250; else: fare = 500. Test data: 4 and 5, 12 and 13 (boundaries), 8 and 30 (normal), −1 (erroneous, which should be rejected).if age > 18:, and indent print("Adult") by 4 spaces. (Also check whether "adult" should be >= 18.)30 < 30 is False, so the outer else runs. Whether 30 % should count as dry is a design decision; the boundary must be chosen deliberately and tested.mark >= 50 first and gets D. The chain must test the highest boundary first.Key points
== != < > <= >= and logic and or not give True or False; chained comparisons such as 0 <= x <= 100 are allowed.if, elif and else lines end with a colon, and their blocks are indented by 4 spaces; indentation replaces ENDIF.if … elif chain only the first True branch runs; check validity first and test from the most demanding condition down.and/or combine conditions into one.Sources and credits
This lesson adapts CC BY-SA material and is shared under CC BY-SA 4.0.
mark = int(input("Mark: "))
if mark >= 50:
print("Pass")
print("Well done")
else:
print("Fail")
print("Result recorded")mark = int(input("Mark (0-100): "))
if not 0 <= mark <= 100:
print("Invalid mark")
elif mark >= 80:
print("Grade A")
elif mark >= 70:
print("Grade B")
elif mark >= 60:
print("Grade C")
elif mark >= 50:
print("Grade D")
else:
print("Grade F")moisture = int(input("Soil moisture (%): "))
hour = int(input("Hour of the day (0-23): "))
if moisture < 30: # the soil is dry
if 11 <= hour <= 15: # the hottest hours
print("Dry, but wait until evening")
else:
print("Pump ON")
else:
print("Soil moist enough: pump OFF")mark = 75
if mark >= 50:
print("Pass")Quick check
Which line correctly starts a test for a mark of exactly 50?