Weeks
Intro to PythonWeek 3 · Loops, range and Formatted Output
Week 3 Notes

Python,
Week 3

Loops, ranges and formatted output: the tools that let a few lines of code do real repetitive work.

8 chapters55 worked examples~47 min read
whilefor and rangef-stringsbreak / continue

Chapters

  1. 01The while LoopPart 1
  2. 02The for Loop and range()Parts 2-3
  3. 03for-Loop PracticePart 3
  4. 04Nested Loops and PracticeParts 4-5
  5. 05Formatted Printing, end and sepParts 6-7
  6. 06break, continue and passPart 8
  7. 07Practice ZonePractice zone
  8. 08Week 3 Summary SheetAll parts
01
Loops

The while Loop

Repeating while a condition holds, with while...else, and four classic digit programs.

1.1The while loop

The while loop executes a group of statements as long as the given expression is True.

Syntax

while expression: followed by an indented block of statement(s).

Python
i = 0
while i < 5:
    print(i)
    i += 1
Output
0
1
2
3
4
i = 0i < 5 ?Trueprint(i)i += 1Falseelse: (if present)the counter changes inside the body; without i += 1 the test never turns False
Figure 1. Test, run the body, update the counter, test again

The loop keeps going until i (the counter) is no longer less than 5. Incrementing the counter is important: if it is not changed, the condition never becomes false and the loop runs forever.

Roundi at the testi < 5 ?printsi after
10True01
21True12
32True23
43True34
54True45
65False—loop ends
Python
i = 0
while i < 5:
    print(i)
    # i += 1 is missing: i stays 0 and this prints 0 forever
Do not run this one. It is shown only to explain the infinite loop. (If it ever happens, stop the program with the Stop button or Ctrl + C.)

1.2while ... else

The else block runs once, when the condition becomes false, that is when the loop ends normally.

Python
i = 1
while i <= 2:
    print("Hello")
    i += 1
else:
    print("Loop end")
Output
Hello
Hello
Loop end
Extra. If the loop is left early with break (Part 6), the else block is skipped.
Python
i = 1
while i <= 5:
    if i == 3:
        break
    print(i)
    i += 1
else:
    print("Loop end")
Output
1
2

1.3Practice: factorial

The factorial of nn is 1×2×⋯×n1 \times 2 \times \cdots \times n. Start with fact = 1 and multiply by i for i = 1, 2, ..., n. Two versions of the same program:

Python
print("Enter a no.: ")
n = int(input())
i, fact = 1, 1
while i <= n:
    fact = fact * i
    i += 1
print("Factorial is:", fact)
Output
Enter a no.: 
5
Factorial is: 120
Python
n = int(input("Enter: "))
i, fact = 1, 1
while i <= n:
    fact = fact * i
    i += 1
print("Factorial:", fact)
Output
Enter: 5
Factorial: 120
ifact beforefact after
111
212
326
4624
524120

For n = 0 the loop never runs, so fact stays 1, which is the correct value of 0!.

1.4Practice: count the digits

Python
num = abs(int(input("Enter a no.: ")))
digits = 1
while num > 9:
    num = num // 10
    digits += 1
print(digits)
Output
Enter a no.: 12345
5

Each pass removes the last digit with // 10 and adds 1 to the count; the loop stops when only one digit is left (num > 9 is false). abs() makes negative numbers work.

InputOutput
123455
91
102
01
-9873
Simpler alternative. len(str(x)) gives the digit count directly: len(str(12345)) is 5.

1.5Practice: reverse the digits

Python
num = int(input("Enter a number: "))
absNum = abs(num)
rev = 0
while absNum > 0:
    r = absNum % 10
    absNum = absNum // 10
    rev = rev * 10 + r
print(rev if num > 0 else -rev)
Output
Enter a number: 123
321

Each pass takes the last digit r = absNum % 10, drops it from absNum, and pushes it onto the right end of rev with rev * 10 + r. Trace for 123:

absNum (start)r = absNum % 10absNum afterrev
1233123
122132
110321
InputOutputNote
123321
-45-54sign restored at the end
1001leading zeros disappear in a number
00the loop never runs

1.6Practice: palindrome check

Python
num = int(input("Enter a number: "))
absNum = abs(num)
rev = 0
while absNum > 0:
    r = absNum % 10
    absNum = absNum // 10
    rev = rev * 10 + r
if num < 0:
    rev = -rev
print("Palindrome" if rev == num else "Not a palindrome")
Output
Enter a number: 121
Palindrome

A number is a palindrome if it reads the same reversed. The program reverses it and compares with the original.

InputOutput
121Palindrome
123Not a palindrome
10Not a palindrome
7Palindrome
-121Palindrome
Extra. The program calls -121 a palindrome because it restores the sign before comparing. By the usual definition negative numbers are not palindromes, so treat that as a quirk of this program.

1.7Going deeper

  • Choose the update. Three things make a good while: a starting value, a test, and an update that moves toward making the test false.
  • Unknown number of rounds. while is the right tool when you do not know in advance how many times to repeat (digits of a number, input until a sentinel).
  • Off-by-one. i < n versus i <= n changes how many times the loop runs (extra).

1.8Loop patterns you will use again and again

Almost every loop question is one of a handful of patterns. Spot the pattern first, then fill in the numbers.

A. Accumulator, counter, flag, running maximum

  • Accumulator: start a variable at the identity (0 for a sum, 1 for a product) and update it every round.
  • Counter: start at 0 and add 1 only when a condition holds.
  • Flag: start with found = False, set it to True when you meet the item, and test it after the loop.
  • Running maximum: start with the first value (not 0, which fails for all-negative data) and replace it whenever a larger value comes.
  • Average: accumulator divided by counter, after the loop.
Python
marks = [7, 3, 6, 2]
total = 0
count = 0
for m in marks:
    total = total + m
    count = count + 1
print("total", total, "count", count, "average", total / count)

temps = [-9, -4, -2, -7]
largest = temps[0]               # start from the first value, not from 0
for t in temps:
    if t > largest:
        largest = t
print("largest", largest)

found = False
for x in [4, 8, 15]:
    if x == 8:
        found = True
print("found", found)
Output
total 18 count 4 average 4.5
largest -2
found True

B. Euclid's gcd and the Fibonacci numbers with a while loop

Python
a, b = 252, 105
while b != 0:
    a, b = b, a % b              # both names change at once
print(a)

x, y = 0, 1
n = 8
while n > 0:
    print(x, end=" " if n > 1 else "\n")
    x, y = y, x + y
    n = n - 1
Output
21
0 1 1 2 3 5 8 13

The line a, b = b, a % b evaluates the whole right side first, then assigns, so it needs no temporary variable. The loop is Euclid's algorithm: gcd⁡(a,b)=gcd⁡(b,a mod b)\gcd(a, b) = \gcd(b, a \bmod b).

C. A loop that stops on a signal (sentinel) and the loop's else

  • Sentinel: while True: keeps going until a special value tells you to stop, then break leaves the loop. This is the pattern for "read numbers until the user types 0".
  • Loop else: the else block of a for or while runs when the loop ends normally, and is skipped if a break ended it. A prime test fits perfectly: if no divisor made us break, the number is prime.
Python
data = [5, 4, 3, 0, 9, 9]     # imagine these come from input()
total = 0
i = 0
while True:
    v = data[i]
    if v == 0:
        break                  # the sentinel
    total = total + v
    i = i + 1
print("sum before the 0 is", total)

for n in [7, 9]:
    for d in range(2, n):
        if n % d == 0:
            print(n, "is not prime")
            break
    else:
        print(n, "is prime")
Output
sum before the 0 is 12
7 is prime
9 is not prime
Off-by-one checklist. range(a, b) stops before b; to include b write range(a, b + 1). A while loop that never changes its condition runs forever; check that the variable in the condition really changes inside the loop.

1.9Exam tips and common mistakes

Exam tips
  • Trace with a table: columns for each variable, one row per round, and a final row for the failed test.
  • Count rounds by asking "when does the test first become false?".
Common mistakes
  • Forgetting to update the counter (infinite loop).
  • Updating the counter before printing and so shifting the output by one.
  • Starting fact at 0, which makes every product 0.

Practice questions (graded-assignment style)

Q1How many lines?

Multiple Choice Question (MCQ): choose the one correct option.

How many numbers does the program print?

Python
i = 0
while i < 5:
    print(i)
    i += 1
1
4
2
5
3
6
4
It never stops
Solution
Idea

Find the first i for which i < 5 is false.

Python
i = 0
while i < 5:
    print(i)
    i += 1
Output
0
1
2
3
4
  • i takes the values 0, 1, 2, 3, 4 inside the loop: five prints. At i = 5 the test fails.
  • Answer: option 2.
Q2Factorial of 4

Numerical Answer Type (NAT).

What does the program print for the input 4?

Python
n = int(input("Enter: "))
i, fact = 1, 1
while i <= n:
    fact = fact * i
    i += 1
print("Factorial:", fact)
Solution
Idea

Multiply 1, 2, 3, 4 in turn.

Python
n = int(input("Enter: "))
i, fact = 1, 1
while i <= n:
    fact = fact * i
    i += 1
print("Factorial:", fact)
Output
Enter: 4
Factorial: 24
  • fact goes 1 → 1 → 2 → 6 → 24.
  • Answer: 24
Q3Digit count

Numerical Answer Type (NAT).

What does the digit-count program print for the input 5000?

Python
num = abs(int(input("Enter a no.: ")))
digits = 1
while num > 9:
    num = num // 10
    digits += 1
print(digits)
Solution
Idea

Each pass removes one digit until one is left.

Python
num = abs(int(input("Enter a no.: ")))
digits = 1
while num > 9:
    num = num // 10
    digits += 1
print(digits)
Output
Enter a no.: 5000
4
  • 5000 → 500 → 50 → 5, three removals, so the count goes 1 → 4.
  • Answer: 4
Q4Reverse with a zero

Multiple Choice Question (MCQ): choose the one correct option.

What does the reverse program print for the input 120?

Python
num = int(input("Enter a number: "))
absNum = abs(num)
rev = 0
while absNum > 0:
    r = absNum % 10
    absNum = absNum // 10
    rev = rev * 10 + r
print(rev if num > 0 else -rev)
1
021
2
21
3
12
4
120
Solution
Idea

rev is a number, not a string.

Python
num = int(input("Enter a number: "))
absNum = abs(num)
rev = 0
while absNum > 0:
    r = absNum % 10
    absNum = absNum // 10
    rev = rev * 10 + r
print(rev if num > 0 else -rev)
Output
Enter a number: 120
21
  • The digits come off as 0, 2, 1, so rev becomes 0, 2, 21. A number cannot keep a leading zero, so the result is 21.
  • Answer: option 2.
Q5while-else

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
i = 1
while i <= 2:
    print(i)
    i += 1
else:
    print("Loop end")
1
1 and 2 only
2
1, 2 and then Loop end
3
Loop end only
4
Nothing
Solution
Idea

The loop ends normally, so else runs.

Python
i = 1
while i <= 2:
    print(i)
    i += 1
else:
    print("Loop end")
Output
1
2
Loop end
  • The condition i <= 2 becomes false after two rounds, so the loop ends normally and else runs.
  • Answer: option 2.
Q6Palindrome

Multiple Choice Question (MCQ): choose the one correct option.

What does the palindrome program print for the input 10?

Python
num = int(input("Enter a number: "))
absNum = abs(num)
rev = 0
while absNum > 0:
    r = absNum % 10
    absNum = absNum // 10
    rev = rev * 10 + r
if num < 0:
    rev = -rev
print("Palindrome" if rev == num else "Not a palindrome")
1
Palindrome
2
Not a palindrome
3
10
4
An error
Solution
Idea

Reverse 10 as a number.

Python
num = int(input("Enter a number: "))
absNum = abs(num)
rev = 0
while absNum > 0:
    r = absNum % 10
    absNum = absNum // 10
    rev = rev * 10 + r
if num < 0:
    rev = -rev
print("Palindrome" if rev == num else "Not a palindrome")
Output
Enter a number: 10
Not a palindrome
  • 10 reversed is the number 1 (the leading zero vanishes), and 1 != 10.
  • Answer: option 2.
Q1A running maximum

Numerical Answer Type (NAT).

What does the program print?

Python
data = [-5, -2, -8]
best = 0
for v in data:
    if v > best:
        best = v
print(best)
Solution
Idea

Starting from 0 assumes the data contains something at least as large as 0.

Python
data = [-5, -2, -8]
best = 0
for v in data:
    if v > best:
        best = v
print(best)
Output
0
  • No value in the list is greater than 0, so best never changes and the program prints 0, which is not even in the list. The correct start is best = data[0], which gives -2.
  • Answer: 0
Q2Euclid with a while loop

Numerical Answer Type (NAT).

What is printed?

Python
a, b = 84, 36
while b != 0:
    a, b = b, a % b
print(a)
Solution
Idea

Trace the pair (a,b)(a, b) round by round.

Python
a, b = 84, 36
while b != 0:
    a, b = b, a % b
print(a)
Output
12
  • (84,36)→(36,12)→(12,0)(84, 36) \to (36, 12) \to (12, 0), since 84 mod 36=1284 \bmod 36 = 12 and 36 mod 12=036 \bmod 12 = 0. The loop stops with a=12a = 12.
  • Answer: 12
Q3The Fibonacci loop

Numerical Answer Type (NAT).

What is the last number printed?

Python
x, y = 0, 1
for _ in range(7):
    print(x, end=" ")
    x, y = y, x + y
Solution
Idea

The loop prints seven terms: each round prints x, then moves the pair along.

Python
x, y = 0, 1
for _ in range(7):
    print(x, end=" ")
    x, y = y, x + y
Output
0 1 1 2 3 5 8 
  • The terms are 0,1,1,2,3,5,80, 1, 1, 2, 3, 5, 8. The seventh is 8.
  • Answer: 8
Q4The loop's else

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
for n in [4, 5]:
    for d in range(2, n):
        if n % d == 0:
            print(n, "composite")
            break
    else:
        print(n, "prime")
1
4 composite then 5 prime
2
4 prime then 5 prime
3
4 composite then 5 composite
4
4 composite, 4 prime, 5 prime
Solution
Idea

The else belongs to the inner for, and runs only if that loop finished without a break.

Python
for n in [4, 5]:
    for d in range(2, n):
        if n % d == 0:
            print(n, "composite")
            break
    else:
        print(n, "prime")
Output
4 composite
5 prime
  • n = 4: d = 2 divides 4, so it prints 4 composite and breaks; the else is skipped.
  • n = 5: no d in 2, 3, 4 divides 5, no break, so else prints 5 prime.
  • Answer: option 1.
Q5Stopping on a sentinel

Numerical Answer Type (NAT).

What does the program print?

Python
data = [3, 6, 0, 10, 10]
total = 0
for v in data:
    if v == 0:
        break
    total += v
print(total)
Solution
Idea

break leaves the loop at the first 0; the numbers after it are never read.

Python
data = [3, 6, 0, 10, 10]
total = 0
for v in data:
    if v == 0:
        break
    total += v
print(total)
Output
9
  • 3+6=93 + 6 = 9. If break were continue, the 0 would just be skipped and the answer would be 3+6+10+10=293 + 6 + 10 + 10 = 29.
  • Answer: 9
Revision overview
Syntaxwhile expression:
indented block
CounterStart, test, update
No update = infinite loop
elseRuns when the test turns
False (not after break)
The while loopWeek 3 · Part 1
Factorialfact = fact * i
Digits// 10 drops a digit
% 10 reads a digit
Reverserev = rev * 10 + r
Revision: repeating while a condition holds
Next · LoopsThe for Loop and range()
02
Loops

The for Loop and range()

Iterating over strings and lists, and counting with range(start, stop, step).

2.1The for loop

The for loop goes through (iterates over) a sequence or iterable object, such as a string or a list. The loop variable takes each item in turn.

Syntax

for variable in sequence: followed by an indented block.

2.2Looping through a list and a string

Python
pets = ["cats", "goats", "dogs"]
for pet in pets:
    print(pet)
Output
cats
goats
dogs
Python
txt = "Hello"
for x in txt:
    print(x)
Output
H
e
l
l
o
for x in "Hello":Hx = "H"ex = "e"lx = "l"lx = "l"ox = "o"current itemoutput, one per line:H e l l o
Figure 2. A string is a sequence of characters, so the loop visits one character per round

2.3The range() function

Use range() when you need to repeat a block but have nothing natural to loop over. range(5) makes the numbers 0, 1, 2, 3, 4: five numbers, starting at 0 by default.

Python
for x in range(5):
    print(x)
Output
0
1
2
3
4
range(start, stop, step)
  • start: the first value (default 0).
  • stop: the end point plus 1; it is never included.
  • step: the increment (default 1; negative to count down).
Python
for x in range(3, 8, 2):
    print(x)
Output
3
5
7
Python
for x in range(5, -1, -1):
    print(x)
Output
5
4
3
2
1
0
range(3, 8, 2)range(5, -1, -1)0123456789stop (not included)start+2+2543210-1stop (not included)startstop is one past the last value you want
Figure 3. The numbers produced by range(3, 8, 2) and range(5, -1, -1)
End point rule. The stop value must be 1 greater than the last value you want (or, counting down, 1 less). For an expected last value of 9, write 10.
CallValuesHow many
range(5)[0, 1, 2, 3, 4]5
range(2, 6)[2, 3, 4, 5]4
range(0, 31, 10)[0, 10, 20, 30]4
range(10, 0, -3)[10, 7, 4, 1]4
range(5, 1)[]0
range(0)[]0

The last two rows are empty ranges (extra): going from 5 up to 1 with step +1, or from 0 up to 0, produces nothing, so a loop over them never runs. list(...) is used here only to display the values.

2.4Going deeper

  • for versus while. Use for when you know what to loop over; use while when you repeat until a condition changes.
  • The variable stays after the loop (extra). After for x in range(3) the name x still holds 2.
  • Do not change the counter yourself. A for loop updates its variable automatically; no i += 1 is needed.
Python
for x in range(3):
    pass
print(x)
Output
2

2.5Exam tips and common mistakes

Exam tips
  • Write the list of values range produces before reading the loop body.
  • Number of rounds of range(start, stop, step) with a positive step is about (stop - start) / step, rounded up.
Common mistakes
  • Expecting range(1, 5) to include 5.
  • Using a positive step to count down (range(5, 0) is empty).
  • Writing range(5, -1) without the -1 step when counting down.

Practice questions (graded-assignment style)

Q1Which values?

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
for x in range(2, 10, 3):
    print(x, end=" ")
1
2 5 8
2
2 5 8 11
3
2 3 4 ... 10
4
3 6 9
Solution
Idea

Start at 2, add 3, stop before 10.

Python
for x in range(2, 10, 3):
    print(x, end=" ")
Output
2 5 8 
  • The values are 2, 5, 8 (the next would be 11, which is not below 10).
  • Answer: option 1.
Q2How many rounds

Numerical Answer Type (NAT).

How many numbers does range(1, 10, 2) produce? The program prints the count.

Python
print(len(range(1, 10, 2)))
Solution
Idea

List them: 1, 3, 5, ...

Python
print(len(range(1, 10, 2)))
Output
5
  • The values are 1, 3, 5, 7, 9: five numbers.
  • Answer: 5
Q3Counting down

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
for x in range(10, 0, -3):
    print(x, end=" ")
1
10 7 4 1
2
10 7 4 1 -2
3
10 7 4
4
Nothing
Solution
Idea

The stop value 0 is never reached, and the step is -3.

Python
for x in range(10, 0, -3):
    print(x, end=" ")
Output
10 7 4 1 
  • 10, 7, 4, 1 are all above 0; the next, -2, is not.
  • Answer: option 1.
Q4Empty range

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
for x in range(5, 1):
    print(x)
print("done")
1
5 4 3 2
2
done only
3
5 then done
4
An error
Solution
Idea

A positive step cannot go from 5 down to 1.

Python
for x in range(5, 1):
    print(x)
print("done")
Output
done
  • range(5, 1) is empty, so the loop body never runs and only the last line prints.
  • Answer: option 2.
Q5Reading a string

Multiple Select Question (MSQ): select all that apply.

Which statements about the program are true?

Python
for x in "Hello":
    print(x)
1
It prints 5 lines
2
Each line holds one character
3
It prints the word on one line
4
The loop variable holds a single character each round
Solution
Idea

A string is a sequence of characters.

Python
for x in "Hello":
    print(x)
Output
H
e
l
l
o
  • "Hello" has 5 characters, each printed on its own line.
  • Answer: options 1, 2 and 4.
Q6Last value

Numerical Answer Type (NAT).

What is the last number printed?

Python
last = 0
for x in range(0, 31, 3):
    last = x
print(last)
Solution
Idea

The stop value is never reached.

Python
last = 0
for x in range(0, 31, 3):
    last = x
print(last)
Output
30
  • range(0, 31, 3) counts 0, 3, ..., 30; 33 would be past 31.
  • Answer: 30
Revision overview
forfor var in sequence:
visits each item
rangerange(n): 0 to n-1
range(a, b, s): a to b-1
Reverserange(5, -1, -1)
5 down to 0
The for loop and range()Week 3 · Part 2
Sequenceslists, strings, ...
Stopnever included
Emptyrange(5, 1) gives nothing
Revision: repeating over a sequence or a range of numbers
Next · Loopsfor-Loop Practice
03
Loops

for-Loop Practice

Six small programs: sums, tables, primes, digits, divisibility and factors.

Six small programs that combine for, range(), if and strings. For each: read the program, check the sample runs, and make sure you can explain every line.

3.1Sum of the first n numbers

Python
sum = 0
n = int(input("Enter a no.: "))
for x in range(1, n + 1):
    sum += x
print("Sum of first", n, "numbers is", sum)
Output
Enter a no.: 5
Sum of first 5 numbers is 15
xsum beforesum after
101
213
336
4610
51015
Extra. The name sum is also a built-in function. Using it as a variable works here but hides the built-in; prefer total.

3.2A multiplication table

Python
for i in range(11):
    print("2 x", i, "=", 2 * i)
Output
2 x 0 = 0
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

range(11) gives 0 to 10, so the table starts at 2 x 0 = 0. Use range(1, 11) to start at 1 (extra).

3.3Is the number prime?

A prime number is greater than 1 and divisible only by 1 and itself. The program assumes flag = True and switches it to False as soon as some i in 2 ... x-1 divides x.

Python
x = int(input("Enter a number: "))
if x > 1:
    flag = True
    for i in range(2, x):
        if x % i == 0:
            flag = False
    print("Prime Number" if flag else "Not a prime number")
else:
    print("Not a prime number")
Output
Enter a number: 7
Prime Number
InputOutputWhy
7Prime Numberno divisor among 2..6
9Not a prime number3 divides 9
2Prime Numberthe range 2..1 is empty, so flag stays True
1Not a prime numbernot greater than 1
0Not a prime numbernot greater than 1

3.4Sum of all digits

Python
x = int(input("Enter a number: "))
sum = 0
for i in str(x):
    sum += int(i)
print("Sum of all digits is", sum)
Output
Enter a number: 1234
Sum of all digits is 10

str(x) turns the number into text, the loop visits each digit character, and int(i) turns it back into a number to add. 1 + 2 + 3 + 4 = 10.

3.5Numbers below x divisible by 3 or 5

Python
x = int(input("Enter a number: "))
for i in range(x):
    if i % 3 == 0 or i % 5 == 0:
        print(i)
Output
Enter a number: 16
0
3
5
6
9
10
12
15

3.6All factors of a number

Python
x = int(input("Enter a no.: "))
for i in range(1, x + 1):
    if x % i == 0:
        print(i)
Output
Enter a no.: 12
1
2
3
4
6
12
InputFactors
121 2 3 4 6 12
71 7
11
361 2 3 4 6 9 12 18 36

3.7Going deeper

  • Early exit (extra). The prime program keeps testing after it finds a divisor. Adding break (Part 6) stops at the first one.
  • Fewer tests (extra). It is enough to test divisors up to the square root of x.
  • Flag pattern. Assume True, loop, set False when you find a counter-example: the same idea works for many "is it always...?" checks.
Python
x = 29
flag = True
for i in range(2, x):
    if x % i == 0:
        flag = False
        break
print("Prime" if flag else "Not prime")
Output
Prime

3.8Exam tips and common mistakes

Exam tips
  • For output questions write out the loop variable values first, then run the body for each.
  • Check the edge inputs: 0, 1, 2 and a negative number.
Common mistakes
  • Using range(1, n) for the sum of the first n numbers (it stops at n - 1).
  • Forgetting int(i) when adding digit characters.
  • Treating 1 as prime.

Practice questions (graded-assignment style)

Q1Sum

Numerical Answer Type (NAT).

What does the sum program print for the input 10?

Python
sum = 0
n = int(input("Enter a no.: "))
for x in range(1, n + 1):
    sum += x
print("Sum of first", n, "numbers is", sum)
Solution
Idea

Add 1 through 10.

Python
sum = 0
n = int(input("Enter a no.: "))
for x in range(1, n + 1):
    sum += x
print("Sum of first", n, "numbers is", sum)
Output
Enter a no.: 10
Sum of first 10 numbers is 55
  • 1 + 2 + ... + 10 = 55.
  • Answer: 55
Q2Prime check

Multiple Choice Question (MCQ): choose the one correct option.

What does the prime program print for the input 15?

Python
x = int(input("Enter a number: "))
if x > 1:
    flag = True
    for i in range(2, x):
        if x % i == 0:
            flag = False
    print("Prime Number" if flag else "Not a prime number")
else:
    print("Not a prime number")
1
Prime Number
2
Not a prime number
3
An error
4
Nothing
Solution
Idea

Does any number from 2 to 14 divide 15?

Python
x = int(input("Enter a number: "))
if x > 1:
    flag = True
    for i in range(2, x):
        if x % i == 0:
            flag = False
    print("Prime Number" if flag else "Not a prime number")
else:
    print("Not a prime number")
Output
Enter a number: 15
Not a prime number
  • 3 and 5 divide 15, so the flag becomes False.
  • Answer: option 2.
Q3Digit sum

Numerical Answer Type (NAT).

What does the digit-sum program print for the input 9045?

Python
x = int(input("Enter a number: "))
sum = 0
for i in str(x):
    sum += int(i)
print("Sum of all digits is", sum)
Solution
Idea

Add the four digits.

Python
x = int(input("Enter a number: "))
sum = 0
for i in str(x):
    sum += int(i)
print("Sum of all digits is", sum)
Output
Enter a number: 9045
Sum of all digits is 18
  • 9 + 0 + 4 + 5 = 18.
  • Answer: 18
Q4Divisible by 3 or 5

Multiple Choice Question (MCQ): choose the one correct option.

For the input 11, what is printed (one number per line)?

Python
x = int(input("Enter a number: "))
for i in range(x):
    if i % 3 == 0 or i % 5 == 0:
        print(i)
1
0 3 5 6 9 10
2
3 5 6 9 10
3
0 3 5 6 9
4
3 5 6 9 10 11
Solution
Idea

range(11) starts at 0 and stops at 10.

Python
x = int(input("Enter a number: "))
for i in range(x):
    if i % 3 == 0 or i % 5 == 0:
        print(i)
Output
Enter a number: 11
0
3
5
6
9
10
  • The numbers 0 to 10 divisible by 3 or 5 are 0, 3, 5, 6, 9, 10.
  • Answer: option 1.
Q5Number of factors

Numerical Answer Type (NAT).

How many lines does the factors program print for the input 36?

Python
x = 36
count = 0
for i in range(1, x + 1):
    if x % i == 0:
        count += 1
print(count)
Solution
Idea

Count the divisors of 36.

Python
x = 36
count = 0
for i in range(1, x + 1):
    if x % i == 0:
        count += 1
print(count)
Output
9
  • The factors of 36 are 1, 2, 3, 4, 6, 9, 12, 18, 36: nine lines.
  • Answer: 9
Q6The prime for 2

Multiple Choice Question (MCQ): choose the one correct option.

What does the prime program print for the input 2?

Python
x = int(input("Enter a number: "))
if x > 1:
    flag = True
    for i in range(2, x):
        if x % i == 0:
            flag = False
    print("Prime Number" if flag else "Not a prime number")
else:
    print("Not a prime number")
1
Prime Number
2
Not a prime number
3
An error
4
Nothing
Solution
Idea

Is 2 > 1? What does range(2, 2) give?

Python
x = int(input("Enter a number: "))
if x > 1:
    flag = True
    for i in range(2, x):
        if x % i == 0:
            flag = False
    print("Prime Number" if flag else "Not a prime number")
else:
    print("Not a prime number")
Output
Enter a number: 2
Prime Number
  • 2 > 1 is true, range(2, 2) is empty, so flag stays True.
  • Answer: option 1.
Revision overview
Sumrange(1, n + 1)
sum += x
Primeflag = True
test 2 .. x-1
False on a divisor
Digitsfor i in str(x)
int(i)
for-loop practiceWeek 3 · Part 3
Divisiblei % 3 == 0 or i % 5 == 0
Factorsx % i == 0 for 1 .. x
Edge cases0, 1, 2, negatives
Revision: small programs built from for, range and if
Next · LoopsNested Loops and Practice
04
Loops

Nested Loops and Practice

Loops inside loops, and four problems built on them.

4.1Nested loops

A loop can sit inside another loop. For every round of the outer loop, the inner loop runs completely from its first value to its last.

Python
animal = ["tiger", "cat", "dog"]
sounds = ["roars", "meows", "barks"]
for x in animal:
    for y in sounds:
        print(f"the {x} {y}")
Output
the tiger roars
the tiger meows
the tiger barks
the cat roars
the cat meows
the cat barks
the dog roars
the dog meows
the dog barks
order of the 9 prints (outer: animal, inner: sound)roarsmeowsbarkstiger123cat456dog789the inner loop restarts from its first value for every outer value
Figure 4. 3 animals × 3 sounds = 9 prints, in this order
Counting rounds

If the outer loop runs m times and the inner loop runs n times each, the inner body runs m × n times in total.

Python
count = 0
for i in range(3):
    for j in range(4):
        count += 1
print(count)
Output
12

4.2Problem 1: all primes below a number

2 is printed separately; then every i from 3 up to num - 1 is tested by an inner loop over j. The break stops the inner loop at the first divisor; the end=' ' keeps the primes on one line.

Python
num = int(input('Enter a no.: '))
if num >= 2:
    print(2, end=' ')
    for i in range(3, num):
        flag = True
        for j in range(2, i):
            if i % j == 0:
                flag = False
                break
        if flag:
            print(i, end=' ')
Output
Enter a no.: 20
2 3 5 7 11 13 17 19 
InputOutput
202 3 5 7 11 13 17 19
122 3 5 7 11
32
22
1(nothing)
Correction (extra). The task says primes below the entered number, but for the input 2 the program prints 2, which is not below 2. Changing the first test to num > 2 fixes it.
InputOriginalFixed (num > 2)
22(nothing)
322
102 3 5 72 3 5 7

4.3Problem 2: profit or loss per trader

The number of traders and trades is unknown, so while loops are used with sentinel values: employee id -1 ends the outer loop, trade amount 0 ends the inner loop for one trader.

Python
empId = input('Enter employee Id: ')
while empId != '-1':
    trade = int(input('Enter trade amount: '))
    pro_loss = 0
    while trade != 0:
        pro_loss += trade
        trade = int(input('Enter trade amount: '))
    print(f"Profit/loss for emp {empId} is {pro_loss}")
    empId = input('\nEnter emp Id: ')
Output
Enter employee Id: 101
Enter trade amount: 100
Enter trade amount: -30
Enter trade amount: 0
Profit/loss for emp 101 is 70

Enter emp Id: 102
Enter trade amount: 50
Enter trade amount: 0
Profit/loss for emp 102 is 50

Enter emp Id: -1
TraderTradesResult
101100, -3070
1025050

4.4Problem 3: day-wise total rainfall

Python
days = int(input('Enter no. of days: '))
for i in range(1, days + 1):
    total = 0
    rainfall = int(input('Enter the rainfall: '))
    while rainfall != -1:
        total += rainfall
        rainfall = int(input('Enter the rainfall: '))
    print(f"Total rainfall for day {i} is {total}")
Output
Enter no. of days: 2
Enter the rainfall: 10
Enter the rainfall: 20
Enter the rainfall: -1
Total rainfall for day 1 is 30
Enter the rainfall: 5
Enter the rainfall: -1
Total rainfall for day 2 is 5

Here the outer loop is a for (the number of days is known) and the inner loop is a while that stops at the sentinel -1. total = 0 is reset at the start of every day.

4.5Problem 4: the longest word

Python
word = input("Enter a word: ")
maxlen = 0
while word != '-1':
    count = 0
    for letter in word:
        count += 1
    if count > maxlen:
        maxlen = count
    word = input("Enter a word: ")
print("The length of the longest word is:", maxlen)
Output
Enter a word: tree
Enter a word: elephant
Enter a word: sun
Enter a word: -1
The length of the longest word is: 8

The inner for counts the letters of each word; maxlen keeps the largest count seen. (A shorter way is len(word), extra.)

Wordcountmaxlen after
tree44
elephant88
sun38

4.6Going deeper

  • Sentinel loops. When you cannot know how many inputs will come, read one value first, then loop while it is not the sentinel, reading the next value at the end of the body.
  • Reset inner variables. A running total for each trader or day must be set to 0 inside the outer loop.
  • Patterns (extra). Nested loops draw grids and triangles: the inner loop prints a row, the outer loop moves to the next row.
Python
for i in range(1, 5):
    for j in range(i):
        print("*", end="")
    print()
Output
*
**
***
****

4.7Exam tips and common mistakes

Exam tips
  • Write the outer values; for each, list the inner values; then read off the output in order.
  • For total counts multiply the number of rounds of the loops.
Common mistakes
  • Forgetting that break leaves only the inner loop.
  • Not resetting total or pro_loss for each trader or day.
  • Forgetting to read the next value at the end of a sentinel loop (infinite loop).

Practice questions (graded-assignment style)

Q1Iteration count

Numerical Answer Type (NAT).

What does the program print?

Python
count = 0
for i in range(4):
    for j in range(5):
        count += 1
print(count)
Solution
Idea

Multiply the two loop lengths.

Python
count = 0
for i in range(4):
    for j in range(5):
        count += 1
print(count)
Output
20
  • The outer loop has 4 rounds and the inner loop has 5 rounds each: 4 × 5 = 20.
  • Answer: 20
Q2Nested output

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
for i in range(1, 3):
    for j in range(1, 3):
        print(i, j)
1
1 1 1 2 2 1 2 2 (pairs, in this order)
2
1 1 2 1 1 2 2 2
3
1 2 2 1
4
Only 2 2
Solution
Idea

The inner loop finishes for each outer value.

Python
for i in range(1, 3):
    for j in range(1, 3):
        print(i, j)
Output
1 1
1 2
2 1
2 2
  • For i = 1: j = 1, 2; then for i = 2: j = 1, 2.
  • Answer: option 1.
Q3Primes below 12

Multiple Choice Question (MCQ): choose the one correct option.

What does the primes-below program print for the input 12?

Python
num = int(input('Enter a no.: '))
if num >= 2:
    print(2, end=' ')
    for i in range(3, num):
        flag = True
        for j in range(2, i):
            if i % j == 0:
                flag = False
                break
        if flag:
            print(i, end=' ')
1
2 3 5 7 11
2
2 3 5 7
3
3 5 7 11
4
2 3 5 7 9 11
Solution
Idea

Which numbers from 2 to 11 are prime?

Python
num = int(input('Enter a no.: '))
if num >= 2:
    print(2, end=' ')
    for i in range(3, num):
        flag = True
        for j in range(2, i):
            if i % j == 0:
                flag = False
                break
        if flag:
            print(i, end=' ')
Output
Enter a no.: 12
2 3 5 7 11 
  • 2, 3, 5, 7 and 11 are prime (11 is below 12).
  • Answer: option 1.
Q4Trader total

Numerical Answer Type (NAT).

For trader 7 the trades are 20, 20, -5 and then 0. What profit/loss does the program print?

Python
empId = input('Enter employee Id: ')
while empId != '-1':
    trade = int(input('Enter trade amount: '))
    pro_loss = 0
    while trade != 0:
        pro_loss += trade
        trade = int(input('Enter trade amount: '))
    print(f"Profit/loss for emp {empId} is {pro_loss}")
    empId = input('\nEnter emp Id: ')
Solution
Idea

The 0 only stops the loop; it is not added.

Python
empId = input('Enter employee Id: ')
while empId != '-1':
    trade = int(input('Enter trade amount: '))
    pro_loss = 0
    while trade != 0:
        pro_loss += trade
        trade = int(input('Enter trade amount: '))
    print(f"Profit/loss for emp {empId} is {pro_loss}")
    empId = input('\nEnter emp Id: ')
Output
Enter employee Id: 7
Enter trade amount: 20
Enter trade amount: 20
Enter trade amount: -5
Enter trade amount: 0
Profit/loss for emp 7 is 35

Enter emp Id: -1
  • 20 + 20 - 5 = 35.
  • Answer: 35
Q5Longest word

Numerical Answer Type (NAT).

For the words sky, python, is and then -1, what length is printed?

Python
word = input("Enter a word: ")
maxlen = 0
while word != '-1':
    count = 0
    for letter in word:
        count += 1
    if count > maxlen:
        maxlen = count
    word = input("Enter a word: ")
print("The length of the longest word is:", maxlen)
Solution
Idea

Compare the lengths 3, 6, 2.

Python
word = input("Enter a word: ")
maxlen = 0
while word != '-1':
    count = 0
    for letter in word:
        count += 1
    if count > maxlen:
        maxlen = count
    word = input("Enter a word: ")
print("The length of the longest word is:", maxlen)
Output
Enter a word: sky
Enter a word: python
Enter a word: is
Enter a word: -1
The length of the longest word is: 6
  • python has 6 letters, the longest word.
  • Answer: 6
Q6break in a nested loop

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)
        break
1
1 1 only
2
1 1 then 2 1 then 3 1
3
1 1, 1 2, 1 3
4
Nothing
Solution
Idea

break ends only the inner loop.

Python
for i in range(1, 4):
    for j in range(1, 4):
        print(i, j)
        break
Output
1 1
2 1
3 1
  • The inner loop stops after printing one pair for each i, but the outer loop keeps going.
  • Answer: option 2.
Revision overview
NestedInner runs fully
for each outer round
m × n rounds
Sentinel-1, 0 end a
while loop of inputs
ResetTotals start at 0
inside the outer loop
Nested loopsWeek 3 · Part 4
Primes below ninner loop + break + flag
fix for n = 2
Longest wordcount letters
keep the maximum
Printend=" " keeps one line
Revision: loops inside loops and sentinel-controlled input
Next · OutputFormatted Printing, end and sep
05
Output

Formatted Printing, end and sep

Three ways to format output, decimal places, and the end/sep parameters of print.

5.1Why format?

A plain print with commas works, but putting several values into one tidy line is easier with formatted printing. There are three tools: the % operator, the format() method and f-strings. All three give the same output.

Python
num, i = 2, 1
print(num, "x", i, "=", num * i)
Output
2 x 1 = 2
the same output three ways (num = 2, i = 1)%'%d x %d = %d' % (num, i, num * i)format()'{0} x {1} = {2}'.format(num, i, num * i)f-stringf"{num} x {i} = {num * i}"2 x 1 = 2f-strings put the variables directly inside the braces
Figure 5. The same line with the three formatting tools

5.2The string modulo operator (%)

Python
num, i = 2, 1
print('%d x %d = %d' % (num, i, num * i))
Output
2 x 1 = 2
SpecifierMeaningExample
%dinteger7
%ffloat (6 decimals by default)3.500000
%.2ffloat with 2 decimals (extra)3.14
%sstring (extra)hi

The values after % go in a tuple, in the same order as the specifiers.

5.3The format() method

Python
num, i = 2, 1
print('{0} x {1} = {2}'.format(num, i, num * i))
Output
2 x 1 = 2

{0} is replaced by the first argument (num), {1} by the second (i) and {2} by the third (num * i). The numbers are positions, counting from 0.

Python
print('{1} {0} {1}'.format('a', 'b'))
Output
b a b

5.4f-strings

Python
num, i = 2, 1
print(f"{num} x {i} = {num * i}")
Output
2 x 1 = 2

Put an f before the opening quote and write variables (even expressions such as num * i) directly inside {}.

Python
num = 2
for i in range(1, 4):
    print(f"{num} x {i} = {num * i}")
Output
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6

5.5Decimal places

A specifier after a colon controls how a number is shown. .3f means "a float with 3 digits after the decimal point"; the value is rounded.

f"{x:.3f}"xthe value:colon.point33 digitsffloatx = 22/7 = 3.142857… → 3.143rounds, it does not just cut: 3.1428… becomes 3.143
Figure 6. Reading {x:.3f}
Python
x = 22/7

# string modulo operator
print('Value of pi: %.3f' % (x))

# format() method
print('Value of pi = {0:.2f}'.format(x))

# f-string
print(f"Value of pi: {x:.3f}")
Output
Value of pi: 3.143
Value of pi = 3.14
Value of pi: 3.143
Correction (extra). The source prints Value of pi : 3.141 for the first and last lines. Running the code gives 3.143, because 22/7 = 3.142857... rounds up at the third decimal. The middle line, with 2 decimals, is 3.14, as in the source.
Python
x = 1234.5678
print(f"{x:.2f}")
print(f"{x:.0f}")
print(f"{x:.1f}")
Output
1234.57
1235
1234.6

5.6print() parameters: end and sep

By default print() ends with a newline (\n) and separates its arguments with a space. end and sep change these.

default: each print ends with a newlineprint("A")print("B")ABend=" " keeps the next print on the same lineprint("A", end=" ")print("B")A Bsep changes the separator between argumentsprint("09","12","2016", sep="-")09-12-2016
Figure 7. What end and sep change
Python
print("Welcome to", end=" ")
print("Python", end=" ")
print("stuck", end="@")
print("home")
Output
Welcome to Python stuck@home
Python
print("G", "F", "E", sep="")
print("09", "12", "2016", sep="-")
Output
GFE
09-12-2016
  • end='' keeps the next output on the same line.
  • sep='' removes the space; any string works as a separator.

5.7Going deeper

  • Which to use (extra). f-strings are the shortest and easiest to read; know all three because exams use all three.
  • An empty print() prints a newline (extra). That is how a row of stars ends before the next row starts.
  • Rounding only changes the display (extra). f"{x:.2f}" shows 2 decimals but x itself is unchanged.
Python
print(1, 2, 3, sep=", ")
x = 3.14159
print(f"{x:.2f}")
print(x)
Output
1, 2, 3
3.14
3.14159

5.8Exam tips and common mistakes

Exam tips
  • Translate each format string into the final text by replacing placeholders one by one.
  • For :.nf count n digits after the point and round the last one.
Common mistakes
  • Forgetting the f before an f-string (the braces then print literally).
  • Writing % with a single value in a tuple of the wrong length.
  • Counting format() positions from 1 instead of 0.

Practice questions (graded-assignment style)

Q1Which format?

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
print('{1} {0} {1}'.format('a', 'b'))
1
b a b
2
a b a
3
0 1 0
4
An error
Solution
Idea

Positions count from 0: {1} is "b".

Python
print('{1} {0} {1}'.format('a', 'b'))
Output
b a b
  • {1} is the second argument b, {0} the first, a.
  • Answer: option 1.
Q2Decimal places

Numerical Answer Type (NAT).

What does the program print?

Python
x = 1234.5678
print(f"{x:.2f}")
Solution
Idea

Two decimals, rounded.

Python
x = 1234.5678
print(f"{x:.2f}")
Output
1234.57
  • 1234.5678 rounded to 2 decimals is 1234.57.
  • Answer: 1234.57
Q3Equivalent lines

Multiple Select Question (MSQ): select all that apply.

Which of these print 3 x 4 = 12?

Python
print('%d x %d = %d', 3, 4, 12)
1
print('%d x %d = %d' % (3, 4, 12))
2
print('{0} x {1} = {2}'.format(3, 4, 12))
3
print(f"3 x 4 = {3 * 4}")
4
print('%d x %d = %d', 3, 4, 12)
Solution
Idea

Option 4 forgets the % operator.

Python
print('%d x %d = %d', 3, 4, 12)
Output
%d x %d = %d 3 4 12
  • Options 1, 2, 3 each produce 3 x 4 = 12.
  • Option 4 passes the format string and numbers as separate arguments, so it prints the raw text followed by the numbers.
  • Answer: options 1, 2 and 3.
Q4end

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
print("A", end="-")
print("B")
1
A-B on one line
2
A and B on two lines
3
AB on one line
4
A B on one line
Solution
Idea

end replaces the newline after the first print.

Python
print("A", end="-")
print("B")
Output
A-B
  • The first print ends with - instead of a newline, so B follows on the same line.
  • Answer: option 1.
Q5sep

Numerical Answer Type (NAT).

What does the program print?

Python
print("2026", "09", "18", sep="-")
Solution
Idea

sep goes between the arguments.

Python
print("2026", "09", "18", sep="-")
Output
2026-09-18
  • The three arguments are joined with - between them.
  • Answer: 2026-09-18
Q6The pi line

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
x = 22/7
print(f"Value of pi: {x:.3f}")
1
3.141
2
3.143
3
3.142
4
3.14
Solution
Idea

22/7 = 3.142857...; round to 3 decimals.

Python
x = 22/7
print(f"Value of pi: {x:.3f}")
Output
Value of pi: 3.143
  • The fourth decimal digit is 8, so the third decimal rounds up from 2 to 3: 3.143.
  • Answer: option 2.
Revision overview
Three tools'%d' % v
'{0}'.format(v)
f'{v}'
Decimals{x:.2f}: 2 decimals,
rounded
Positionsformat() counts from 0
Formatted printingWeek 3 · Part 5
endwhat print ends with
default newline
sepbetween arguments
default space
Source fixpi to 3 places is 3.143
Revision: showing values neatly with print
Next · Controlbreak, continue and pass
06
Control

break, continue and pass

Three statements that change how a loop runs from the inside.

These three statements change how a loop runs from the inside.

for i in 1 … 5break12345stops at 3continue12345skips 3pass12345nothing changes
Figure 8. The same loop over 1 to 5 with break, continue and pass at 3

6.1break: leave the loop

break stops the current loop entirely; execution continues after the loop.

Python
x = "Hello @ World"
for i in x:
    if i == "@":
        break
    print(i, end="")
Output
Hello 
Python
i = 1
while i <= 5:
    if i == 3:
        break
    print(i)
    i += 1
Output
1
2

The first program prints Hello (with the trailing space) and stops at @. The second prints 1 and 2; at i = 3 the loop ends.

6.2continue: skip to the next round

continue ends only the current round and jumps straight to the next one.

Python
txt = "hello"
for x in txt:
    if x == "l":
        continue
    print(x)
Output
h
e
o
Extra: a trap with while. In a while loop, put the counter update before continue, or the loop can stick forever on the same value.
Python
i = 0
while i < 5:
    i += 1
    if i == 3:
        continue
    print(i)
Output
1
2
4
5

6.3pass: do nothing

pass is a placeholder. Python needs at least one statement in a block; pass fills the gap and does nothing when executed.

Python
if 5 == 5:
    pass
else:
    pass
print("Hello World")
Output
Hello World
StatementEffectCode after it in the round
breakleaves the whole loopskipped
continuejumps to the next roundskipped
passnothingruns normally

6.4Going deeper

  • break and else (extra). A loop's else runs only if the loop was not left by break. That makes it a handy "not found" branch.
  • Nested loops (extra). break and continue affect only the loop they are directly inside.
  • Why pass (extra). It lets you write the shape of a program first and fill the blocks in later.
Python
for n in range(2, 7):
    for d in range(2, n):
        if n % d == 0:
            break
    else:
        print(n, "is prime")
Output
2 is prime
3 is prime
5 is prime

6.5Exam tips and common mistakes

Exam tips
  • Mark the round where the condition first becomes true, then decide whether the later rounds exist (continue) or not (break).
  • Watch end="" in output questions: the printed text is on one line.
Common mistakes
  • Mixing up break (stop everything) and continue (skip one round).
  • Using continue before the counter update in a while loop.
  • Thinking pass skips the rest of the loop body.

Practice questions (graded-assignment style)

Q1break

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
for i in range(1, 6):
    if i == 3:
        break
    print(i, end=" ")
1
1 2
2
1 2 3
3
1 2 4 5
4
3
Solution
Idea

break ends the loop when i == 3.

Python
for i in range(1, 6):
    if i == 3:
        break
    print(i, end=" ")
Output
1 2 
  • The loop prints 1 and 2, and leaves at 3 before printing it.
  • Answer: option 1.
Q2continue

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
for i in range(1, 6):
    if i == 3:
        continue
    print(i, end=" ")
1
1 2 4 5
2
1 2
3
1 2 3 4 5
4
3
Solution
Idea

continue skips only the round for 3.

Python
for i in range(1, 6):
    if i == 3:
        continue
    print(i, end=" ")
Output
1 2 4 5 
  • When i == 3 the print is skipped, but rounds 4 and 5 still run.
  • Answer: option 1.
Q3First multiple of 7

Numerical Answer Type (NAT).

What does the program print?

Python
for i in range(1, 101):
    if i % 7 == 0:
        print(i)
        break
Solution
Idea

The loop stops at the first multiple of 7.

Python
for i in range(1, 101):
    if i % 7 == 0:
        print(i)
        break
Output
7
  • range(1, 101) reaches 7 first, prints it and breaks.
  • Answer: 7
Q4Count with continue

Numerical Answer Type (NAT).

What does the program print?

Python
count = 0
for i in range(1, 11):
    if i % 3 == 0:
        continue
    count += 1
print(count)
Solution
Idea

Count the numbers from 1 to 10 that are not multiples of 3.

Python
count = 0
for i in range(1, 11):
    if i % 3 == 0:
        continue
    count += 1
print(count)
Output
7
  • The multiples of 3 are 3, 6, 9, so 10 - 3 = 7 numbers are counted.
  • Answer: 7
Q5pass

Multiple Choice Question (MCQ): choose the one correct option.

What does the program print?

Python
for i in range(3):
    pass
1
0 1 2 on three lines
2
Nothing
3
pass
4
An error
Solution
Idea

pass does nothing.

Python
for i in range(3):
    pass
Output
  • The loop runs three times but each round only executes pass, so nothing is printed.
  • Answer: option 2.
Q6break versus continue

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
break ends the whole loop
2
continue ends the whole loop
3
continue skips the rest of the current round
4
pass skips the rest of the current round
Solution
Idea

Recall the table.

  • break leaves the loop; continue skips to the next round.
  • pass does nothing and the rest of the round still runs.
  • Answer: options 1 and 3.
Revision overview
breakStops the loop
entirely
continueSkips to the
next round
passPlaceholder
does nothing
break, continue, passWeek 3 · Part 6
elseSkipped after break
NestedAffects the inner loop only
Counterupdate before continue
Revision: steering a loop from inside
Next · PracticePractice Zone
07
Practice

Practice Zone

The source's ten tasks with worked, executed solutions.

The ten practice tasks from the source, each with a worked solution that was actually run. Try each one yourself first.

Example 1Q1 · while loop

Print all even numbers from 1 to 20 using a while loop.

Solution

Idea: Start at 2 and step by 2.

Python
i = 2
while i <= 20:
    print(i, end=" ")
    i += 2
Output
2 4 6 8 10 12 14 16 18 20 
Example 2Q2 · while ... else

Print the numbers 1 to 5, then print Done once the loop ends.

Solution

Idea: else runs when the test turns false.

Python
i = 1
while i <= 5:
    print(i, end=" ")
    i += 1
else:
    print("Done")
Output
1 2 3 4 5 Done
Example 3Q3 · for loop

Loop through the string "EngiKode" and print each character.

Solution

Idea: A string is iterable.

Python
for ch in "EngiKode":
    print(ch, end=" ")
Output
E n g i K o d e 
Example 4Q4 · range()

Print every 3rd number from 0 to 30 using range().

Solution

Idea: The stop value is 31 so 30 is included.

Python
for x in range(0, 31, 3):
    print(x, end=" ")
Output
0 3 6 9 12 15 18 21 24 27 30 
Example 5Q5 · nested loops

Print a 5 × 5 grid of stars using nested for loops.

Solution

Idea: The inner loop prints a row; the empty print() ends it.

Python
for i in range(5):
    for j in range(5):
        print("*", end="")
    print()
Output
*****
*****
*****
*****
*****
Example 6Q6 · formatted printing

Print 3 x 4 = 12 using all three formatting methods.

Solution

Idea: All three give the same text.

Python
a, b = 3, 4
print('%d x %d = %d' % (a, b, a*b))
print('{0} x {1} = {2}'.format(a, b, a*b))
print(f"{a} x {b} = {a*b}")
Output
3 x 4 = 12
3 x 4 = 12
3 x 4 = 12
Example 7Q7 · end / sep

Print 2026-09-18 from three separate values using sep.

Solution

Idea: sep joins the values with a dash.

Python
print('2026', '09', '18', sep='-')
Output
2026-09-18
Example 8Q8 · break

Loop through 1 to 100 and stop as soon as you hit a number divisible by 7.

Solution

Idea: break after the first hit.

Python
for i in range(1, 101):
    if i % 7 == 0:
        print(i)
        break
Output
7
Example 9Q9 · continue

Print the numbers 1 to 10, skipping multiples of 3.

Solution

Idea: continue jumps over the print for 3, 6, 9.

Python
for i in range(1, 11):
    if i % 3 == 0:
        continue
    print(i, end=" ")
Output
1 2 4 5 7 8 10 
Example 10Q10 · combined

Write a program that finds all prime numbers between 1 and 50.

Solution

Idea: Test each number against the smaller ones; break at the first divisor.

Python
for num in range(2, 51):
    flag = True
    for i in range(2, num):
        if num % i == 0:
            flag = False
            break
    if flag:
        print(num, end=" ")
Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 
Note on the source. The source lists these tasks and the solution code without printed output. The outputs shown here come from running the code. The solutions above use end=" " to keep numbers on one line; printing one per line works equally well.

7.1Exam tips and common mistakes

Exam tips
  • Say aloud what the loop variable is in each round before writing the body.
  • Test with a small input and compare with a hand count.
Common mistakes
  • Starting range at 0 when the task says 1.
  • Using range(30) when 30 itself must be included.
  • Forgetting the empty print() that ends a pattern row.

Practice questions (graded-assignment style)

Q1Even numbers

Multiple Choice Question (MCQ): choose the one correct option.

How many numbers does the Q1 program print?

Python
i = 2
count = 0
while i <= 20:
    count += 1
    i += 2
print(count)
1
9
2
10
3
11
4
20
Solution
Idea

List 2, 4, ..., 20.

Python
i = 2
count = 0
while i <= 20:
    count += 1
    i += 2
print(count)
Output
10
  • The even numbers from 2 to 20 are ten numbers.
  • Answer: option 2.
Q2Stars

Numerical Answer Type (NAT).

How many * characters does the grid program print in total?

Python
total = 0
for i in range(5):
    for j in range(5):
        total += 1
print(total)
Solution
Idea

5 rows of 5.

Python
total = 0
for i in range(5):
    for j in range(5):
        total += 1
print(total)
Output
25
  • 5 outer rounds × 5 inner rounds = 25 stars.
  • Answer: 25
Q3Number of primes

Numerical Answer Type (NAT).

How many prime numbers are there between 1 and 50?

Python
count = 0
for num in range(2, 51):
    flag = True
    for i in range(2, num):
        if num % i == 0:
            flag = False
            break
    if flag:
        count += 1
print(count)
Solution
Idea

Count the output of Q10.

Python
count = 0
for num in range(2, 51):
    flag = True
    for i in range(2, num):
        if num % i == 0:
            flag = False
            break
    if flag:
        count += 1
print(count)
Output
15
  • The primes are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47: fifteen of them.
  • Answer: 15
Q4Skipping

Multiple Choice Question (MCQ): choose the one correct option.

What is the sum of the numbers the Q9 program prints?

Python
total = 0
for i in range(1, 11):
    if i % 3 == 0:
        continue
    total += i
print(total)
1
55
2
37
3
40
4
45
Solution
Idea

Add all of 1 to 10 and subtract the multiples of 3.

Python
total = 0
for i in range(1, 11):
    if i % 3 == 0:
        continue
    total += i
print(total)
Output
37
  • 55 - (3 + 6 + 9) = 37.
  • Answer: option 2.
Revision overview
while taskseven numbers
while ... else
for tasksstring, range, stars
formatting, sep
Controlbreak, continue
primes to 50
Practice zoneWeek 3 · Part 7
MethodPredict, run, compare
Edgefirst and last value
Outputone line with end=" "
Revision: turning the Week 3 tools into small programs
Next · All partsWeek 3 Summary Sheet
08
All parts

Week 3 Summary Sheet

One page to revise all of Week 3: loops, formatting, loop control and the exam checklist.

The big picture

Part 1 · while
  • Repeats while the test is True; update the counter.
  • else runs when the loop ends normally.
Part 2 · for and range
  • for visits each item of a sequence.
  • range(start, stop, step); stop excluded.
Part 3 · for practice
  • Sum, table, prime, digit sum, factors.
  • Flag pattern: assume True, set False.
Part 4 · Nested loops
  • Inner loop runs fully per outer round.
  • Sentinel input loops; reset inner totals.
Part 5 · Formatting
  • %d %f, format(), f-strings, :.nf.
  • end and sep in print.
Part 6 · break, continue, pass
  • break stops the loop.
  • continue skips a round; pass does nothing.
Part 7 · Practice zone
  • Ten tasks with real outputs.
  • Primes up to 50: fifteen of them.

Revision sheet

TopicKey point
whileruns while a condition is True
while...elseelse runs once the loop ends normally
foriterates over a sequence / iterable
range(n)0 to n-1
range(a, b, step)a to b-1, stepping by step
Reverse rangerange(5, -1, -1) gives 5 down to 0
Nested loopsa loop placed inside another loop
%d %fmodulo-style format specifiers
.format(){0} {1} {2} positional placeholders
f-stringsvariables directly inside {}
{x:.2f}decimal-place format specifier
end=''changes what print() ends a line with
sep=''changes the separator between print() arguments
breakstops the loop entirely
continueskips to the next iteration
passdoes nothing; syntactic placeholder

Which loop when?

SituationUse
repeat a fixed number of timesfor i in range(n)
go through every item or characterfor x in sequence
repeat until something changes or input endswhile
stop at the first matchbreak
ignore some itemscontinue
leave a block empty for nowpass

Exam checklist (from the source)

  • while loop syntax and counter increments.
  • while...else.
  • for loop over lists and strings.
  • range() with 1, 2 and 3 arguments.
  • Reverse iteration with range().
  • Nested loops.
  • Factorial, digit count, reverse, palindrome patterns.
  • Prime-check logic (single and nested-loop versions).
  • % modulo formatting.
  • .format() with positional placeholders.
  • f-strings and decimal-place specifiers.
  • end and sep parameters.
  • break versus continue.
  • pass as a placeholder.

Common mistakes

No counter update
  • A while without an update runs forever.
range off by one
  • The stop value is never included.
Inner totals not reset
  • Set running totals to 0 inside the outer loop.
break vs continue
  • break leaves the loop; continue skips one round.
f-string without f
  • Without the f the braces print literally.
Trusting printed pi
  • 22/7 to 3 places is 3.143, not 3.141.
Back to top