Conditions
Write a small program that transforms data using conditions, loops and functions.
THE IDEA
Choosing a branch
So far every line ran. An if statement lets the program choose. It evaluates a condition, an expression that comes out True or False, and runs its indented block only when the condition is true. With elif and else you build a chain: Python checks the conditions from the top and runs the first block whose condition is true, then skips the rest.
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"score >= 90:False, try the next onescore >= 80:True, so grade = "B"score >= 70:never checkedgrade is "B"
Only one branch ever runs. Drag across 90, 80 and 70: with >= the boundary value itself belongs to the higher grade.
Indentation is part of the code
In Python the 4 spaces in front of a line are not decoration: they say which lines belong to the branch. A line at the left margin always runs; an indented line runs only when its condition holds.
score = 55
if score >= 70:
print("passed")
print("well done") # inside the branch: skipped for 55
score = 55
if score >= 70:
print("passed")
print("well done") # not indented: prints for every scoreBuilding conditions: comparing and combining
Comparisons are == (equal), !=, <, <=, > and >=. Combine booleans with and, or and not. The remainder operator % is handy for tests such as divisibility: year % 4 == 0.
a and b | False | true only when both are true |
a or b | True | true when at least one is true |
not a | False | flips it |
Check yourself first
Predict first. With x = 3, which branch of if x >= 3: ... else: ... runs?
Predict first. The chain tests score >= 70 first, then elif score >= 90. What happens for a score of 95?
Chapter context
A program is a precise sequence of state changes. Python names refer to objects; reading a program means tracking the values those names refer to, rather than guessing from how the code sounds.
TRY IT YOURSELF
Exercise 1: turn a score into a grade
- Set
gradewith anif/elif/elsechain: 90 or more is "A", 80 to 89 is "B", 70 to 79 is "C", anything lower is "F". - Python checks the conditions top to bottom and runs only the first one that is true. Watch the edge values 90, 80 and 70.
Exercise 2: combine conditions
- A year is a leap year when it is divisible by 4, except century years (divisible by 100), which only count when divisible by 400.
- Set
is_leapto True or False. A single boolean expression with%,==,and,orand parentheses works, and so does anif/else. year % 4 == 0is true when 4 divides year. Careful:==compares,=assigns.
Both exercises must be solved to finish this lesson.
Stuck, or something not working? You can come back to it any time.
CHECK YOUR UNDERSTANDING
Which branch runs for x = 3 and if x >= 3?
Chapter reference: math, worked example & code
This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.
Math and notation
For an accumulator over numbers :
The subscript denotes a step, not a Python index. After the last step, is the sum. For a mean, divide by the number of items, and define what should happen for an empty list.
Worked example
Trace a robot's forward distances [2, 1, 3]. Position starts at zero and changes to 2, then 3, then 6. Replacing three copy-pasted moves with a loop preserves the order and final state. A mean distance is 6/3 = 2; the count is 3, not the last list index 2.
Reference code
The following example uses the Python standard library and does not call a remote service.
moves = [2, 1, 3]
position = 0
for distance in moves:
position += distance
assert position == 6
assert sum(moves) / len(moves) == 2
Python examples are provided for study and local execution; this page does not execute Python.
Common mistakes
Assignment does not copy a mutable object. A loop stop value is exclusive. A function can return None even when its print output looks correct.