6. Flow of control in Python
About this chapter
Big idea: Python runs lines in order. You can choose a path. You can repeat a block.
This is an original lesson that follows the Class 11 Computer Science syllabus. Read the key words first. Cover a worked answer and try the steps yourself before you look. For a program, say what it will print before you read the real output.
- Tell sequence, selection and repetition apart.
- Write if, if-else and elif chains with a true colon and matching indent.
- Explain why Python treats indentation as part of the language.
- Use a for loop with range(start, stop, step) and say exactly which numbers appear.
- Write a while loop with a counter that eventually makes the test false.
- Use break and continue, and nest loops to print a table or a star shape.
In 1966 two results showed a limit. Sequence, selection and repetition are enough for any program. Corrado Böhm and Giuseppe Jacopini published that proof. Structured programming then taught people to use if and loops. Free jumps with GOTO made programs hard to follow. Edsger Dijkstra argued against those jumps. Python was first released by Guido van Rossum in 1991. It made indentation part of the language. A block is visible on the page. Its for loop walks a sequence. Its while loop repeats while a test stays true. break and continue were already familiar from earlier languages such as C.
6.1 Selection
A program can walk one path. Or it can choose.
The order of statements is flow of control.
Until now, most programs used sequence.
Sequence means line 1, then line 2, then line 3.
It is one path. There is no turn.
How to read the figure. Start at the top. Follow the arrows. There is only one way down.
left = 19
right = 7
diff = left - right
print(diff)12This program always subtracts 7 from 19. The difference is 12.
There is no test. So there is no choice.
Python also needs two other patterns.
Selection means choose one path from two or more.
Repetition means run the same block again.
This section builds selection. Later sections build repetition.
- Flow of control: the order in which statements run.
- Sequence: run statements one after another, with no choice.
- Selection: choose which block to run after a test.
- Repetition: run a block more than once.
A condition is a test. It is true or false.
An if statement runs a block only when the test is true.
If the test is false, Python skips that block.
Write if, then the test, then a colon.
The next lines of the if must be indented.
Those indented lines are a block. They stay together.
if condition:
statement(s)Here the pass mark is 50. A score of 72 is at least 50.
So the block runs.
score = 72
if score >= 50:
print('Pass')PassWould the same if print Pass for a score of 49?
Goal. Predict whether Pass prints.
Rule. The if block runs only when the test is true.
Compare. 49 is less than 50. 49 is still below the mark.
Test. score >= 50 is false.
Action. Python skips the indented print.
Result: No. A false if does not run its block.
An if-else statement gives two paths.
The if block runs when the test is true.
The else block runs when the test is false.
Exactly one of the two blocks runs.
Never both. Never neither.
if condition:
statement(s)
else:
statement(s)How to read the figure. The diamond is the test. Yes means true. No means false. Follow only one arrow. Both arrows meet at End.
Only one path of an if-else runs.
score = 41
if score >= 50:
print('Pass')
else:
print('Try again')Try again41 is below 50. So the else path prints Try again.
Sometimes you need more than two paths.
elif means else if.
Python checks the first if.
If that is false, it checks the next elif.
It stops at the first true test.
It runs that one block. It skips the rest.
An optional else at the end catches leftover cases.
if condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)A cabin bag may be too heavy, fine, or very light.
Only one message should print.
grams = 850
if grams > 1000:
print('Too heavy')
elif grams > 500:
print('OK for cabin')
else:
print('Very light')OK for cabin850 is not greater than 1000. The first test is false.
850 is greater than 500. The elif block runs.
Python never looks at the else.
A bag weighs 1200 grams. Which message prints, and why?
Goal. Name the one printed message.
Rule. The first true test wins in an if-elif chain.
First test. 1200 is greater than 1000. True.
Action. The first block runs.
Later tests. Python does not check elif or else.
Result: Too heavy. The first true test wins.
A nested if is an if inside another if or elif.
Use it when a second question needs the first answer.
Division needs a second check. You cannot divide by zero.
first = 24
second = 6
op = '/'
if op == '/':
if second == 0:
print('Cannot divide')
else:
print(first / second)
else:
print('Unknown')4.024 divided by 6 is 4. Python 3 prints 4.0 because / gives a float.
The inner else ran because second was not 0.
| Form | When to use it |
|---|---|
| if | One extra block, only when a test is true. |
| if-else | Two paths: true path and false path. |
| if-elif-else | Three or more paths, tested from the top. |
| nested if | A second test that depends on the first. |
How to read the table. Stay on one row. Match the form to the number of paths you need.
Cover the answers. Try each item on paper first.
6.2 Indentation
Spaces at the start of a line mark a Python block.
Indentation is the blank space at the start of a line.
Many languages wrap a block in curly brackets.
Python does not. Indentation is the block.
The same indent means the same block.
A deeper indent means a nested block.
This is syntax, not decoration.
Syntax means the writing rules of the language.
Wrong indent is a syntax error. Python stops.
- Indentation: leading spaces or tabs that group statements into a block.
- Syntax: the writing rules of the language.
- Block: a group of statements at the same indent, under a header that ends with a colon.
A common habit is four spaces for each extra level.
Keep the same style in one file.
Do not mix tabs and spaces.
Every compound header needs a colon.
That includes if, elif, else, for and while.
The colon says a block starts on the next line.
first = 11
second = 8
if first > second:
print('first is larger')
print('done')
else:
print('second is larger')
print('still done')first is larger
doneBoth print lines under the if share the same indent.
They are one block.
The else block did not run. 11 is greater than 8.
| Line kind | Indent |
|---|---|
| if first > second: | No extra indent. This is the header. |
| print('first is larger') | One extra level. Inside the if. |
| print('done') | The same extra level. Still inside the if. |
| else: | Back to the if indent. New header. |
| print('second is larger') | One extra level. Inside the else. |
How to read the table. The header has no extra indent. Body lines sit one level in. else lines up with if.
In Python, indent is part of the language.
A student lines up print('done') with the if, not with the first print. What changes?
Goal. Say what print done does after the move.
Rule. Same indent means same block. Less indent ends the block.
Change. done is no longer inside the if.
Effect. It runs after the choice, on every path.
Result: done would always print, even when the else path ran.
How to read the figure. Follow the four steps. A new unindented line is outside the block.
| Mistake | What you see |
|---|---|
| No colon after if or else | SyntaxError. The program does not start. |
| Body not indented | IndentationError. Python names the line. |
| Tabs mixed with spaces | IndentationError, or a silent wrong group. |
| = used where == is needed | A syntax error, or a logic fault. |
| else lined up too far in | else is treated as inside the if. Error. |
How to read the table. The left column is the typing fault. The right column is the clue Python gives.
Nested if, loops inside if, and loops inside loops add one more indent level.
Count the levels. Match them on the way back out.
Pause here. Answer before you scroll to the answers.
6.3 Repetition
A loop repeats a block. You do not copy the same line a hundred times.
Printing 1 to 4 by hand is easy. Printing 1 to 100000 is not.
Repetition, also called iteration, means run a block again.
A loop is the construct that does that.
Each loop has a changing value, or a sequence of items.
The loop must have a way to stop.
If the stopping test never becomes false, you get an infinite loop.
The program never ends. That is a logic error.
- Loop: a construct that repeats a block.
- Iteration: one pass through the loop body.
- Control variable: the value the loop uses to decide whether to continue.
- Infinite loop: a loop whose stopping test never becomes false.
A for loop walks through a sequence.
The sequence can be a string, a list, or a range of numbers.
The loop variable takes each item in turn.
When the items are finished, the loop ends.
You know in advance how many times it will run.
for item in sequence:
statement(s)How to read the figure. The diamond asks if another item remains. Yes runs the body. Then Python asks again. No goes to End.
A string is a sequence of characters. This loop prints each letter of PLANT.
for letter in 'PLANT':
print(letter)P
L
A
N
TA list is a sequence too. This loop prints four square numbers.
for n in [4, 9, 16, 25]:
print(n)4
9
16
25You can put an if inside a for. This loop prints only the even values.
for n in [3, 8, 11, 14, 19, 22]:
if n % 2 == 0:
print(n)8
14
22Even means the remainder after dividing by 2 is 0.
8, 14 and 22 pass that test. 3, 11 and 19 do not.
range builds a sequence of integers.
You almost always use it with for.
Call it as range(start, stop, step).
start is the first value.
stop is the first value that is not included.
step is the jump.
If you write only range(n), start is 0 and step is 1.
The values are 0, 1, 2, up to n minus 1.
If you omit step, step is 1.
All three arguments must be integers.
step may be negative. It cannot be 0.
Wrap range in list(...) to see the exact values. These results come from a real Python run.
>>> list(range(6))
[0, 1, 2, 3, 4, 5]
>>> list(range(3, 9))
[3, 4, 5, 6, 7, 8]
>>> list(range(1, 13, 3))
[1, 4, 7, 10]
>>> list(range(8, 0, -2))
[8, 6, 4, 2]| Call | Values produced |
|---|---|
range(6) | [0, 1, 2, 3, 4, 5] |
range(3, 9) | [3, 4, 5, 6, 7, 8] |
range(1, 13, 3) | [1, 4, 7, 10] |
range(8, 0, -2) | [8, 6, 4, 2] |
How to read the table. Read one row. The right cell is the full list. The stop value is never in that list.
Look at range(1, 13, 3). Start at 1. Add 3 each time: 4, then 7, then 10.
The next add would be 13. That is not less than 13. So 13 is excluded.
The stop value of range is never in the list.
What numbers does range(2, 11, 3) produce?
Goal. List every integer the call produces.
Rule. Start at 2. Add 3 while the value is less than 11.
Round 1. n is 2. Keep it. Next is 5.
Round 2. n is 5. Keep it. Next is 8.
Round 3. n is 8. Keep it. Next is 11.
Stop. 11 is the stop value. Leave it out.
Result: The values are 2, 5, 8.
| Round | Value of n | n + 3 | Keep n? |
|---|---|---|---|
| 1 | 2 | 5 | Yes, 2 < 11 |
| 2 | 5 | 8 | Yes, 5 < 11 |
| 3 | 8 | 11 | Yes, 8 < 11 |
| 4 | 11 | — | No. 11 is stop, so the loop ends |
How to read the trace. Each row is one candidate. The last row is stop. It is not printed.
A for loop with range can scale a times pattern. This prints the first four multiples of 12.
for n in range(1, 5):
print(n * 12)12
24
36
48The last line is 4 × 12 = 48. range(1, 5) is 1, 2, 3, 4. Five is the stop, so 5 never appears.
A while loop repeats as long as its condition is true.
Python tests the condition before the body.
If the test is already false, the body never runs. Not even once.
while condition:
statement(s)How to read the figure. The diamond is checked before every repeat. Yes prints count, then adds 1, then goes back. No ends the loop.
You must change something inside the body so the test can become false.
A counter that grows or shrinks is the usual pattern.
count = 1
total = 0
while count <= 4:
print(count)
total = total + count
count = count + 1
print(total)1
2
3
4
10Trace this while loop. Fill a table for every round.
Goal. Show count, the print, and the next count on each round.
Rule. Test count <= 4 before the body. Then print. Then add 1 to count. Then add count into total.
Round 1. count is 1. Print 1. count becomes 2. total becomes 1.
Round 2. count is 2. Print 2. count becomes 3. total becomes 3.
Round 3. count is 3. Print 3. count becomes 4. total becomes 6.
Round 4. count is 4. Print 4. count becomes 5. total becomes 10.
Stop. count is 5. 5 <= 4 is false. Print total after the loop.
Result: Prints 1, then 2, then 3, then 4, then 10.
| Start of round | count | Printed | count after add 1 |
|---|---|---|---|
| 1 | 1 | 1 | 2 |
| 2 | 2 | 2 | 3 |
| 3 | 3 | 3 | 4 |
| 4 | 4 | 4 | 5 |
How to read the trace table. One row is one iteration. The last add makes count 5. That fails the test. The loop stops.
Write a for loop that prints the same numbers and the same total.
Goal. Convert the while into a for with range.
Rule. while count <= 4 with count starting at 1 matches range(1, 5).
Why 5. The stop value is excluded. So 1, 2, 3, 4 still run.
Body. Print count. Add count into total. Do not add 1 by hand. for does that.
After. Print total once, after the loop.
Result: for count in range(1, 5) with the same total update prints the same output.
total = 0
for count in range(1, 5):
print(count)
total = total + count
print(total)1
2
3
4
10What if the line count = count + 1 is missing from the while?
Goal. Name the fault.
Rule. A while test must become false, or the loop never ends.
Change. count stays 1.
Test. count <= 4 stays true forever.
Result: An infinite loop. Always change the counter.
A while loop can search. This one prints every factor of 18.
A factor of n is a whole number that divides n with remainder 0.
n = 18
k = 1
while k <= n:
if n % k == 0:
print(k)
k = k + 11
2
3
6
9
1818 divided by 5 leaves remainder 3, so 5 is not a factor. 18 divided by 3 leaves remainder 0, so 3 is a factor.
Write a short answer. Then check the notes below.
6.4 Break and continue
Leave a loop early. Or skip just this round.
A normal loop runs until its sequence ends. Or until its while test is false.
Two extra tools change that.
break leaves the loop at once.
continue skips the rest of this round. Then it tries the next item.
- break: jump out of the nearest loop and continue after it.
- continue: skip the rest of this iteration and go to the next one.
How to read the figure. From the body, Yes on break goes to End. Yes on continue goes back to the loop test. No finishes the body, then returns to the test.
break ends the loop. continue ends only this round.
When Python hits break, it stops the current loop.
Lines after the loop still run.
Lines in the loop after break do not run on that pass.
There is no next pass.
for n in range(1, 12):
if n == 7:
break
print(n)
print('stopped')1
2
3
4
5
6
stoppedrange(1, 12) could have gone up to 11.
When n becomes 7, break fires. 7 is not printed.
The message stopped is after the loop, so it still prints.
| n | Test n == 7 | Action |
|---|---|---|
| 1 to 6 | false | print n |
| 7 | true | break; leave the loop |
| 8 to 11 | never reached | the loop already ended |
How to read the table. Rows 1 to 6 print. Row 7 leaves. Later n values never run.
break is useful in a search. Once you know 21 has a factor, you do not need more tests.
n = 21
found = False
for d in range(2, n):
if n % d == 0:
found = True
break
if found:
print('not prime')
else:
print('prime')not prime21 divided by 3 is exactly 7, remainder 0. found becomes True and break ends the for. The program reports not prime.
When Python hits continue, it does not leave the loop.
It only skips the rest of the body for this item.
The next item still gets a turn.
for n in range(1, 8):
if n % 3 == 0:
continue
print(n)1
2
4
5
73 and 6 are multiples of 3, so continue skips their print.
1, 2, 4, 5 and 7 still print.
The loop ends in the normal way when range is finished.
| n | n % 3 == 0? | Printed? |
|---|---|---|
| 1 | no | yes |
| 2 | no | yes |
| 3 | yes | no, continue |
| 4 | no | yes |
| 5 | no | yes |
| 6 | yes | no, continue |
| 7 | no | yes |
How to read the table. A yes in the middle column means skip the print. The loop still continues.
Replace continue with break in that last program. What prints?
Goal. Predict the output after the swap.
Rule. break leaves the whole loop. continue would only skip one item.
First multiple of 3. That value is 3.
Action. break leaves there.
Already printed. 1 and 2.
Result: 1, then 2, then the program leaves the loop.
A for or while may have an else block.
That else runs when the loop ends the normal way.
If break fired, the else is skipped.
for n in range(1, 4):
print(n)
else:
print('finished')1
2
3
finishedNo break. So finished prints after 1, 2 and 3.
for n in range(1, 4):
if n == 2:
break
print(n)
else:
print('finished')1break fired at 2. So finished does not print. Only 1 prints.
Test yourself on these. Then read the explained answers.
6.5 Nested loops
A loop inside another loop is a nested loop.
A nested loop is a loop in the body of another loop.
The outer loop starts one round.
The inner loop then runs all the way.
Then the outer loop starts the next round.
Python does not limit how deep you nest.
for and while may nest in any mix.
- Nested loop: a loop placed inside the body of another loop.
- Outer loop: the loop that runs more slowly; each of its rounds contains a full inner loop.
- Inner loop: the loop that completes all its iterations during one outer round.
How to read the figure. Do not start the next outer round until the inner loop is done.
for row in range(1, 4):
print('row', row)
for col in range(1, 3):
print(col)
print('inner done')row 1
1
2
inner done
row 2
1
2
inner done
row 3
1
2
inner doneThe outer loop has three rounds: row 1, 2, 3.
Each round, the inner loop prints 1 then 2.
Then inner done prints, still inside the outer loop.
A times table is a nested pattern even when the outer value is fixed.
The inner loop walks the multipliers.
n = 8
for i in range(1, 6):
print(n, 'x', i, '=', n * i)8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40The last line is 8 × 5 = 40. range(1, 6) stops before 6, so there is no 8 × 6 line.
| i | 8 x i | Product |
|---|---|---|
| 1 | 8 x 1 | 8 |
| 2 | 8 x 2 | 16 |
| 3 | 8 x 3 | 24 |
| 4 | 8 x 4 | 32 |
| 5 | 8 x 5 | 40 |
How to read the table. Each row is one inner round. i is the multiplier. The product column is 8 times i.
String multiplication repeats a character.
'' 3 is ***.
A for loop that grows the count builds a triangle.
for i in range(1, 5):
print('*' * i)*
**
***
****Round 1 prints one star. Round 4 prints four.
The shape is a right triangle of stars.
An inner loop can build a line of numbers.
The outer loop chooses how long that line is.
for i in range(1, 4):
line = ''
for j in range(1, i + 1):
line = line + str(j) + ' '
print(line)1
1 2
1 2 3When i is 3, the inner loop prints 1 2 3 on one line.
When a pattern has rows and columns, let the outer loop be the row.
Nested work is not only loop-in-loop.
A for can sit inside if-elif-else.
Factorial uses that shape.
The factorial of a positive whole number n is 1 × 2 × ... × n.
The factorial of 0 is 1.
Negative numbers have no factorial in this lesson.
n = 6
fact = 1
if n < 0:
print('no factorial')
elif n == 0:
print(1)
else:
for i in range(1, n + 1):
fact = fact * i
print(fact)7201 × 2 × 3 × 4 × 5 × 6 = 720. The else branch ran because 6 is positive. The for loop did the multiply.
What does the same program print for n = 0?
Goal. Predict the output when n is 0.
Rule. Check if, then elif, then else. Only one branch runs.
if. 0 is not less than 0. False.
elif. n is 0. True.
for. The loop never starts.
Result: It prints 1, the agreed factorial of 0.
Predict first. Then compare with the notes.
'' 4 print?Summary
- Flow of control is the order statements run: sequence, selection, or repetition.
- if runs a block when a test is true. if-else picks one of two blocks. elif chains extra tests from the top.
- A colon ends the header. The indented lines under it are the block.
- Indentation is syntax in Python, not just tidy layout.
- for walks a sequence. range(start, stop, step) makes integers. stop is excluded.
- while repeats while a test is true, checked before each body. Update the counter or the loop never ends.
- break leaves the loop. continue skips the rest of this round. Loop else runs only if break did not fire.
- A nested loop runs the inner loop fully on every outer round. That is how tables and star shapes are built.
Exercises
These questions are new. Show your thinking. For programs, write your answer before you run the code.
6.1 What is the difference between else and elif after an if?
6.2 What is range for, and what does list(range(6)) produce?
6.3 Difference between break and continue?
6.4 What is an infinite loop? Give a cause.
6.5 Predict the output of this program.
a = 88
while a > 80:
print(a)
a = a - 36.6 Predict the output of this program.
for i in range(12, 20, 3):
print(i)6.7 Predict the output of this program.
for ch in 'MAPS':
print(ch)6.8 Predict the output of this program.
i = 0
total = 0
while i < 9:
if i % 4 == 0:
total = total + i
i = i + 2
print(total)6.9 Predict the output of this program.
for x in range(1, 4):
for y in range(2, 5):
if x * y > 8:
break
print(x * y)6.10 Predict the output of this program.
n = 6
while n > 0:
print(n)
n = n - 1
if n == 3:
break
print('go')6.11 Predict the output of this program.
mark = 73
if mark >= 90:
print('A')
elif mark >= 80:
print('B')
elif mark >= 70:
print('C')
else:
print('D')6.12 Predict the output of this program.
print(list(range(9, 2, -2)))6.13 Predict the output of this program.
for i in range(1, 4):
print('#' * i)6.14 Predict the output of this program.
p = 1
for i in range(1, 5):
p = p * i
print(p)6.15 Predict the output of this program.
for n in range(1, 9):
if n % 4 == 0:
continue
print(n)6.16 Predict the output of this program.
k = 2
while k < 7:
print(k)
k = k + 26.17 Predict the output of this program.
word = 'LOOP'
for ch in word:
if ch == 'O':
break
print(ch)6.18 Predict the output of this program.
for a in range(1, 3):
for b in range(1, 4):
print(a * b)6.19 Why does range(1, 5) not include 5?
6.20 A while test is false at the start. How many times does the body run?
6.21 When does a for-else block run?
Answers
- 6.1: else has no extra test and runs when every test above was false. elif has its own test and runs only when that test is the first true one.
- 6.2: range builds a sequence of integers for loops. list(range(6)) is [0, 1, 2, 3, 4, 5].
- 6.3: break leaves the loop. continue skips the rest of this round and tries the next item.
- 6.4: A loop that never stops. A common cause is a while whose counter never changes.
- 6.5: prints 88, then 85, then 82
- 6.6: prints 12, then 15, then 18
- 6.7: prints M, then A, then P, then S
- 6.8: 12
- 6.9: prints 2, then 3, then 4, then 4, then 6, then 8, then 6
- 6.10: prints 6, then go, then 5, then go, then 4
- 6.11: C
- 6.12: [9, 7, 5, 3]
- 6.13: prints #, then ##, then ###
- 6.14: 24 (this is 4 factorial, 24)
- 6.15: prints 1, then 2, then 3, then 5, then 6, then 7
- 6.16: prints 2, then 4, then 6
- 6.17: L
- 6.18: prints 1, then 2, then 3, then 2, then 4, then 6
- 6.19: The stop value is excluded. The sequence stops at the last integer still less than 5 when the step is positive.
- 6.20: Zero. The test is checked before the body.
- 6.21: When the for loop finishes its sequence without hitting break.