Scroll to turn the page
Intro to Programming · Intro to Programming in Python
if, while and for
A program’s lines run in order, one after another, until something changes the flow: a condition that decides whether a block runs, or a loop that runs a block again and again.
n = 4096 total = 0 while n > 0: total += n % 10 n //= 10 print(total)
19 The figure runs it. While n is above 0, the loop’s body runs: n % 10 is the last digit, added to total, and n //= 10 drops that digit. After 4 passes, n is 0, the condition is False, and the program goes on past the loop to print 19, the sum of the digits of 4096.
| pass | n after it | total after it |
|---|---|---|
| 1 | 409 | 6 |
| 2 | 40 | 15 |
| 3 | 4 | 15 |
| 4 | 0 | 19 |
A table like this, one row per pass with each name’s value, is a trace: the surest way to see what a loop does, and to find where it goes wrong.
The lines inside the loop are its body, marked by indentation: Python has no braces, so the indent itself says which lines belong to the while. Four spaces per level is the convention. The line that opens a block ends with a colon.
comparisons, and, or, not
A condition is an expression whose value is True or False. The comparisons ==, !=, <, <=, > and >= each give one.
age = 16 print(age >= 13 and age <= 19) print(13 <= age <= 19) print(not age > 18) print(age == 16 or age / 0 > 1) print(bool(0), bool(""), bool("0")) True True True True False False True = assigns and == compares: age == 16 asks a question, age = 16 binds a name. and is True when both sides are, or when at least one is, and not flips a value. not binds tightest, then and, then or. Python also allows chained comparisons: 13 <= age <= 19 means 13 <= age and age <= 19.
and and or short-circuit: they stop as soon as the answer is known. In line 5, age == 16 is already True, so or never evaluates age / 0, and there is no ZeroDivisionError: it prints True. Putting the safe test first (x != 0 and 10 / x > 1) is a common guard. They also give back the operand that decided, not always True or False: "" or "guest" and 0 and 5 are guest and 0.
Any value can stand in a condition. Falsy values count as False: False, None, 0, 0.0, the empty string and empty containers. Everything else is truthy, even the string "0": the last line prints False False True.
the first true condition wins
if runs its block only when its condition is true. elif (“else if”) adds another test, tried only if every test above it was false, and else catches whatever is left.
score = 83 if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else: grade = "F" print(grade)
B The tests run top to bottom, and the first true one wins: its block runs, and the rest of the chain is skipped. A score of 83 fails score >= 90, passes score >= 80, and gets 'B'; it is also at least 70, but that test is never made. The figure drops four scores down the ladder.
| score | first true test | grade |
|---|---|---|
| 95 | score >= 90 | "A" |
| 83 | score >= 80 | "B" |
| 74 | score >= 70 | "C" |
| 61 | else | "F" |
So the order of the tests matters: with score >= 70 first, every passing score would get a C. An if needs neither elif nor else; without else, nothing runs when every test is false. Separate if statements, unlike an elif chain, are each tested on their own.
repeat until the condition is false
A while loop tests its condition, runs its body if the condition is true, and goes back to test again. When the test is false, the program carries on after the loop.
n = 1 steps = 0 while n <= 20: n *= 2 steps += 1 print(n, steps)
32 5 n doubles on each pass: 2, 4, 8, 16, 32. After 5 passes it is 32, the test n <= 20 is false, and the loop ends. The body never runs with n above 20, but n can end up above it: the test happens only at the top of each pass.
Each pass must move toward making the condition false. If nothing in the body changes n, the loop never ends: an infinite loop (stop a running program with Ctrl-C). If the condition is false from the start, the body runs zero times.
Use while when the number of passes isn’t known in advance: until the user types “quit”, until a value is close enough, until the digits run out.
one pass per item
A for loop runs its body once for each item of a sequence, binding the loop variable to each in turn. range makes a sequence of integers to loop over.
print(list(range(5))) print(list(range(2, 6))) print(list(range(2, 11, 3))) print(list(range(10, 0, -3)))
[0, 1, 2, 3, 4] [2, 3, 4, 5] [2, 5, 8] [10, 7, 4, 1] | call | counts |
|---|---|
range(stop) | 0, 1, 2, … up to but not including stop |
range(start, stop) | start, start + 1, … not including stop |
range(start, stop, step) | start, start + step, …, stopping before stop; a negative step counts down |
The figure hops along the integers. stop is never included, so range(5) has exactly 5 values, 0 to 4, and range(a, b) has b - a. range(2, 11, 3) stops at 8, since the next step, 11, isn’t below 11. With a negative step, range(10, 0, -3) counts down while above 0.
for ch in "abc": print(ch.upper(), end=" ") print()
A B C A string is a sequence too: for ch in "abc" takes its characters in order. Use for when the passes are known (each item, or n times), and while when they aren’t.
a total and a count, built up pass by pass
Many loops build up an answer: a name set before the loop (the accumulator), updated on each pass, and used after it.
total = 0 count = 0 for k in range(1, 6): if k % 2 == 1: total += k count += 1 print(total, count)
9 3 total and count start at 0. The loop visits k = 1 to 5; the if lets only the odd ones through, so total becomes 1, 4, then 9 (1 + 3 + 5) and count 3. The figure shows each name change as it happens.
The pattern has three parts, and each mistake has a classic symptom. Forget to set the accumulator before the loop and the first += raises a NameError. Set it inside the loop and it restarts on every pass. Print it inside the loop and you get every partial total instead of the answer.
The start value fits the operation: 0 for a sum or a count, 1 for a product, "" for building a string, and the first item (or None) for a maximum.
a loop inside a loop
A loop’s body can hold another loop. The inner loop runs all of its passes for every single pass of the outer one.
for row in range(1, 4): line = "" for col in range(row): line += "*" print(line)
* ** *** The outer loop sets row to 1, 2 and 3. For each, line starts empty and the inner loop adds one star per pass, row passes in all, before the line is printed. The inner range depends on the outer variable, which makes the triangle; the inner body runs 1 + 2 + 3 = 6 times in all.
With fixed ranges the count multiplies: an outer loop of 10 passes around an inner loop of 10 runs the inner body 100 times. That product is what makes nested loops slow on large data (Chapter 7).
Indentation shows which loop a line belongs to: print(line) is in the outer loop’s body but not the inner one’s, so it runs once per row.
leaving a loop early
continue skips the rest of the current pass and goes on to the next. break leaves the loop at once.
n = 60 while True: n += 1 if n % 2 == 0: continue if n % 7 == 0: break print(n)
63 while True never stops on its own: the break is the only way out. 61 is odd but not a multiple of 7; 62 is even, so continue skips the test below it; 63 is odd and a multiple of 7, so break ends the loop. Python goes to the first line after the loop.
for d in range(2, 7): if 7 % d == 0: print("divisible by", d) break else: print("7 is prime") 7 is prime A loop can have an else block, which runs only if the loop finished without a break. Here no divisor from 2 to 6 divides 7, the loop runs out, and the else reports that 7 is prime. break and continue affect only the innermost loop they are in.