←
Class 11 Computer Science
6. Flow of control in Python · 6 / 11
⌕
Chapter 6 of 11

6. Flow of control in Python

8 sections · 5,772 words

About this chapter

240 words · 1 min read

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

998 words · 5 min read

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.

Run the first lineRun the next lineKeep going to the last lineStop
Sequence. One path. No test. No repeat.

How to read the figure. Start at the top. Follow the arrows. There is only one way down.

Python
left = 19
right = 7
diff = left - right
print(diff)

Output
12

This 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.

Python
if condition:
    statement(s)

Here the pass mark is 50. A score of 72 is at least 50.

So the block runs.

Python
score = 72
if score >= 50:
    print('Pass')

Output
Pass

Would 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.

Python
if condition:
    statement(s)
else:
    statement(s)
Startscore = 50?(true or false)Yesprint PassNoprint Try againEnd
An if-else decision. The diamond asks one yes-or-no question. Only one path runs.

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.

Python
score = 41
if score >= 50:
    print('Pass')
else:
    print('Try again')

Output
Try again

41 is below 50. So the else path prints Try again.

A pass mark of 50 includes 50. The test uses >=, not >.

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.

Python
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.

Python
grams = 850
if grams > 1000:
    print('Too heavy')
elif grams > 500:
    print('OK for cabin')
else:
    print('Very light')

Output
OK for cabin

850 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.

Python
first = 24
second = 6
op = '/'
if op == '/':
    if second == 0:
        print('Cannot divide')
    else:
        print(first / second)
else:
    print('Unknown')

Output
4.0

24 divided by 6 is 4. Python 3 prints 4.0 because / gives a float.

The inner else ran because second was not 0.

FormWhen to use it
ifOne extra block, only when a test is true.
if-elseTwo paths: true path and false path.
if-elif-elseThree or more paths, tested from the top.
nested ifA 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.

Read from the top. The first true condition is the only block that runs in an if-elif chain.

Cover the answers. Try each item on paper first.

Watch out: Forgot the colon after if, elif or else? That is a syntax error. Python will not even start.

⚡ Quick Check Flashcards5 questions
Question 1
What is selection?
Try answering before revealing!
Question 2
How many blocks run in one if-else?
Try answering before revealing!
Question 3
What does elif mean?
Try answering before revealing!
Question 4
A score is 50 and the test is score >= 50. Which path runs?
Try answering before revealing!
Question 5
Why nest an if inside a divide branch?
Try answering before revealing!

6.2 Indentation

647 words · 3 min read

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.

Python
first = 11
second = 8
if first > second:
    print('first is larger')
    print('done')
else:
    print('second is larger')
    print('still done')

Output
first is larger
done

Both 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 kindIndent
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.

Write the header and a colon.Indent every line of the block the same.Dedent to end the block.The next unindented line runs after the block.
How Python reads a block

How to read the figure. Follow the four steps. A new unindented line is outside the block.

MistakeWhat you see
No colon after if or elseSyntaxError. The program does not start.
Body not indentedIndentationError. Python names the line.
Tabs mixed with spacesIndentationError, or a silent wrong group.
= used where == is neededA syntax error, or a logic fault.
else lined up too far inelse 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.

If Python says IndentationError, look at that line and the line above. One of them is at the wrong depth.

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.

Watch out: Python cares about indent. A line that looks almost right can still be a syntax error.

⚡ Quick Check Flashcards4 questions
Question 1
What groups statements into a Python block?
Try answering before revealing!
Question 2
Is indentation optional in Python?
Try answering before revealing!
Question 3
What must sit at the end of if, elif, else, for and while?
Try answering before revealing!
Question 4
What happens if you mix tabs and spaces?
Try answering before revealing!

6.3 Repetition

1,562 words · 7 min read

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.

Python
for item in sequence:
    statement(s)
Startanother item?Yesrun body with itemNoEnd
A for loop. The diamond asks if another item is left. Yes runs the body. No ends the loop.

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.

Python
for letter in 'PLANT':
    print(letter)

Output
P
L
A
N
T

A list is a sequence too. This loop prints four square numbers.

Python
for n in [4, 9, 16, 25]:
    print(n)

Output
4
9
16
25

You can put an if inside a for. This loop prints only the even values.

Python
for n in [3, 8, 11, 14, 19, 22]:
    if n % 2 == 0:
        print(n)

Output
8
14
22

Even 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.

Python
>>> 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]
CallValues 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.

RoundValue of nn + 3Keep n?
125Yes, 2 < 11
258Yes, 5 < 11
3811Yes, 8 < 11
411—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.

Python
for n in range(1, 5):
    print(n * 12)

Output
12
24
36
48

The 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.

Python
while condition:
    statement(s)
Startcount = 4?Yesprint countcount = count + 1NoEnd
A while loop. The diamond is checked before every repeat. When the answer is no, the loop stops.

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.

Python
count = 1
total = 0
while count <= 4:
    print(count)
    total = total + count
    count = count + 1
print(total)

Output
1
2
3
4
10

Trace 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 roundcountPrintedcount after add 1
1112
2223
3334
4445

How to read the trace table. One row is one iteration. The last add makes count 5. That fails the test. The loop stops.

Set count to 1.If count = 4 is false, stop.Print count, then add 1.Go back to the test.
The four steps of this while loop

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.

Python
total = 0
for count in range(1, 5):
    print(count)
    total = total + count
print(total)

Output
1
2
3
4
10
for is usual when you know the sequence. while is usual when you keep going until a test fails.

What 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.

Python
n = 18
k = 1
while k <= n:
    if n % k == 0:
        print(k)
    k = k + 1

Output
1
2
3
6
9
18

18 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.

Watch out: A while with no counter update never stops. Always change the counter.

⚡ Quick Check Flashcards5 questions
Question 1
What does range(4) produce?
Try answering before revealing!
Question 2
Does range(1, 5) include 5?
Try answering before revealing!
Question 3
When is a while body skipped completely?
Try answering before revealing!
Question 4
Name the two Python loop kinds.
Try answering before revealing!
Question 5
What is the last number printed by for n in range(1, 5): print(n * 12)?
Try answering before revealing!

6.4 Break and continue

817 words · 4 min read

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.
Loop bodybreak here?YesEnd loopNocontinue?YesNofinish body
break leaves the loop. continue skips the rest of this round and tries the next item.

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.

Python
for n in range(1, 12):
    if n == 7:
        break
    print(n)
print('stopped')

Output
1
2
3
4
5
6
stopped

range(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.

nTest n == 7Action
1 to 6falseprint n
7truebreak; leave the loop
8 to 11never reachedthe 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.

Python
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')

Output
not prime

21 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.

Python
for n in range(1, 8):
    if n % 3 == 0:
        continue
    print(n)

Output
1
2
4
5
7

3 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.

nn % 3 == 0?Printed?
1noyes
2noyes
3yesno, continue
4noyes
5noyes
6yesno, continue
7noyes

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.

Python
for n in range(1, 4):
    print(n)
else:
    print('finished')

Output
1
2
3
finished

No break. So finished prints after 1, 2 and 3.

Python
for n in range(1, 4):
    if n == 2:
        break
    print(n)
else:
    print('finished')

Output
1

break fired at 2. So finished does not print. Only 1 prints.

Loop else is easy to mix up with if-else. It belongs to the loop, not to an if.
break means I am finished with this whole loop. continue means I am finished with this one item.

Test yourself on these. Then read the explained answers.

Watch out: break and continue affect the nearest loop only. They do not jump out of an outer loop.

⚡ Quick Check Flashcards5 questions
Question 1
What does break do?
Try answering before revealing!
Question 2
What does continue do?
Try answering before revealing!
Question 3
After break, do later items in range still run?
Try answering before revealing!
Question 4
When does a loop else run?
Try answering before revealing!
Question 5
Why did 21 count as not prime?
Try answering before revealing!

6.5 Nested loops

788 words · 4 min read

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.
Start one outer roundRun the inner loop to the endFinish the rest of the outer bodyNext outer round, or stop
Nested loops. Inner finishes fully on every outer round.

How to read the figure. Do not start the next outer round until the inner loop is done.

Python
for row in range(1, 4):
    print('row', row)
    for col in range(1, 3):
        print(col)
    print('inner done')

Output
row 1
1
2
inner done
row 2
1
2
inner done
row 3
1
2
inner done

The 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.

Python
n = 8
for i in range(1, 6):
    print(n, 'x', i, '=', n * i)

Output
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40

The last line is 8 × 5 = 40. range(1, 6) stops before 6, so there is no 8 × 6 line.

i8 x iProduct
18 x 18
28 x 216
38 x 324
48 x 432
58 x 540

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.

Python
for i in range(1, 5):
    print('*' * i)

Output
*
**
***
****

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.

Python
for i in range(1, 4):
    line = ''
    for j in range(1, i + 1):
        line = line + str(j) + ' '
    print(line)

Output
1 
1 2 
1 2 3

When 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.

Python
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)

Output
720

1 × 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.

Rows and columns: outer loop is the row. Inner loop is the column.

Predict first. Then compare with the notes.

Watch out: The inner loop must sit one indent deeper. Same indent means two separate loops, not nested loops.

⚡ Quick Check Flashcards5 questions
Question 1
What is a nested loop?
Try answering before revealing!
Question 2
How many times does the inner loop run if the outer loop has 3 rounds and the inner loop has 2?
Try answering before revealing!
Question 3
What does '' 4 print?
Try answering before revealing!
Question 4
What is 6 factorial?
Try answering before revealing!
Question 5
Who runs faster, the inner loop or the outer loop?
Try answering before revealing!

Summary

142 words · 1 min read
  • 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.
Explain each important word in your own words. Then say why the rule works.

Exercises

578 words · 3 min read

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.

Python
a = 88
while a > 80:
    print(a)
    a = a - 3

6.6 Predict the output of this program.

Python
for i in range(12, 20, 3):
    print(i)

6.7 Predict the output of this program.

Python
for ch in 'MAPS':
    print(ch)

6.8 Predict the output of this program.

Python
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.

Python
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.

Python
n = 6
while n > 0:
    print(n)
    n = n - 1
    if n == 3:
        break
    print('go')

6.11 Predict the output of this program.

Python
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.

Python
print(list(range(9, 2, -2)))

6.13 Predict the output of this program.

Python
for i in range(1, 4):
    print('#' * i)

6.14 Predict the output of this program.

Python
p = 1
for i in range(1, 5):
    p = p * i
print(p)

6.15 Predict the output of this program.

Python
for n in range(1, 9):
    if n % 4 == 0:
        continue
    print(n)

6.16 Predict the output of this program.

Python
k = 2
while k < 7:
    print(k)
    k = k + 2

6.17 Predict the output of this program.

Python
word = 'LOOP'
for ch in word:
    if ch == 'O':
        break
    print(ch)

6.18 Predict the output of this program.

Python
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

  1. 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.
  2. 6.2: range builds a sequence of integers for loops. list(range(6)) is [0, 1, 2, 3, 4, 5].
  3. 6.3: break leaves the loop. continue skips the rest of this round and tries the next item.
  4. 6.4: A loop that never stops. A common cause is a while whose counter never changes.
  5. 6.5: prints 88, then 85, then 82
  6. 6.6: prints 12, then 15, then 18
  7. 6.7: prints M, then A, then P, then S
  8. 6.8: 12
  9. 6.9: prints 2, then 3, then 4, then 4, then 6, then 8, then 6
  10. 6.10: prints 6, then go, then 5, then go, then 4
  11. 6.11: C
  12. 6.12: [9, 7, 5, 3]
  13. 6.13: prints #, then ##, then ###
  14. 6.14: 24 (this is 4 factorial, 24)
  15. 6.15: prints 1, then 2, then 3, then 5, then 6, then 7
  16. 6.16: prints 2, then 4, then 6
  17. 6.17: L
  18. 6.18: prints 1, then 2, then 3, then 2, then 4, then 6
  19. 6.19: The stop value is excluded. The sequence stops at the last integer still less than 5 when the step is positive.
  20. 6.20: Zero. The test is checked before the body.
  21. 6.21: When the for loop finishes its sequence without hitting break.
Up next
Continue to the next chapter