Python,
Week 3
Loops, ranges and formatted output: the tools that let a few lines of code do real repetitive work.
Chapters
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.
while expression: followed by an indented block of statement(s).
i = 0
while i < 5:
print(i)
i += 10
1
2
3
4The 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.
| Round | i at the test | i < 5 ? | prints | i after |
|---|---|---|---|---|
| 1 | 0 | True | 0 | 1 |
| 2 | 1 | True | 1 | 2 |
| 3 | 2 | True | 2 | 3 |
| 4 | 3 | True | 3 | 4 |
| 5 | 4 | True | 4 | 5 |
| 6 | 5 | False | — | loop ends |
i = 0
while i < 5:
print(i)
# i += 1 is missing: i stays 0 and this prints 0 foreverCtrl + C.)1.2while ... else
The else block runs once, when the condition becomes false, that is when the loop ends normally.
i = 1
while i <= 2:
print("Hello")
i += 1
else:
print("Loop end")Hello
Hello
Loop endbreak (Part 6), the else block is skipped.i = 1
while i <= 5:
if i == 3:
break
print(i)
i += 1
else:
print("Loop end")1
21.3Practice: factorial
The factorial of is . Start with fact = 1 and multiply by i for i = 1, 2, ..., n. Two versions of the same program:
print("Enter a no.: ")
n = int(input())
i, fact = 1, 1
while i <= n:
fact = fact * i
i += 1
print("Factorial is:", fact)Enter a no.:
5
Factorial is: 120n = int(input("Enter: "))
i, fact = 1, 1
while i <= n:
fact = fact * i
i += 1
print("Factorial:", fact)Enter: 5
Factorial: 120| i | fact before | fact after |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 6 |
| 4 | 6 | 24 |
| 5 | 24 | 120 |
For n = 0 the loop never runs, so fact stays 1, which is the correct value of 0!.
1.4Practice: count the digits
num = abs(int(input("Enter a no.: ")))
digits = 1
while num > 9:
num = num // 10
digits += 1
print(digits)Enter a no.: 12345
5Each 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.
| Input | Output |
|---|---|
| 12345 | 5 |
| 9 | 1 |
| 10 | 2 |
| 0 | 1 |
| -987 | 3 |
len(str(x)) gives the digit count directly: len(str(12345)) is 5.1.5Practice: reverse the digits
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)Enter a number: 123
321Each 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 % 10 | absNum after | rev |
|---|---|---|---|
| 123 | 3 | 12 | 3 |
| 12 | 2 | 1 | 32 |
| 1 | 1 | 0 | 321 |
| Input | Output | Note |
|---|---|---|
| 123 | 321 | |
| -45 | -54 | sign restored at the end |
| 100 | 1 | leading zeros disappear in a number |
| 0 | 0 | the loop never runs |
1.6Practice: palindrome check
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")Enter a number: 121
PalindromeA number is a palindrome if it reads the same reversed. The program reverses it and compares with the original.
| Input | Output |
|---|---|
| 121 | Palindrome |
| 123 | Not a palindrome |
| 10 | Not a palindrome |
| 7 | Palindrome |
| -121 | Palindrome |
-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.
whileis 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 < nversusi <= nchanges 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 (
0for a sum,1for a product) and update it every round. - Counter: start at
0and add1only when a condition holds. - Flag: start with
found = False, set it toTruewhen 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.
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)total 18 count 4 average 4.5
largest -2
found TrueB. Euclid's gcd and the Fibonacci numbers with a while loop
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 - 121
0 1 1 2 3 5 8 13The 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: .
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, thenbreakleaves the loop. This is the pattern for "read numbers until the user types 0". - Loop else: the
elseblock of afororwhileruns when the loop ends normally, and is skipped if abreakended it. A prime test fits perfectly: if no divisor made usbreak, the number is prime.
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")sum before the 0 is 12
7 is prime
9 is not primerange(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
- 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?".
- Forgetting to update the counter (infinite loop).
- Updating the counter before printing and so shifting the output by one.
- Starting
factat 0, which makes every product 0.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
How many numbers does the program print?
i = 0
while i < 5:
print(i)
i += 1Find the first i for which i < 5 is false.
i = 0
while i < 5:
print(i)
i += 10
1
2
3
4itakes the values 0, 1, 2, 3, 4 inside the loop: five prints. Ati = 5the test fails.- Answer: option 2.
Numerical Answer Type (NAT).
What does the program print for the input 4?
n = int(input("Enter: "))
i, fact = 1, 1
while i <= n:
fact = fact * i
i += 1
print("Factorial:", fact)Multiply 1, 2, 3, 4 in turn.
n = int(input("Enter: "))
i, fact = 1, 1
while i <= n:
fact = fact * i
i += 1
print("Factorial:", fact)Enter: 4
Factorial: 24factgoes 1 → 1 → 2 → 6 → 24.- Answer: 24
Numerical Answer Type (NAT).
What does the digit-count program print for the input 5000?
num = abs(int(input("Enter a no.: ")))
digits = 1
while num > 9:
num = num // 10
digits += 1
print(digits)Each pass removes one digit until one is left.
num = abs(int(input("Enter a no.: ")))
digits = 1
while num > 9:
num = num // 10
digits += 1
print(digits)Enter a no.: 5000
4- 5000 → 500 → 50 → 5, three removals, so the count goes 1 → 4.
- Answer: 4
Multiple Choice Question (MCQ): choose the one correct option.
What does the reverse program print for the input 120?
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)0212112120rev is a number, not a string.
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)Enter a number: 120
21- The digits come off as 0, 2, 1, so
revbecomes 0, 2, 21. A number cannot keep a leading zero, so the result is21. - Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
i = 1
while i <= 2:
print(i)
i += 1
else:
print("Loop end")1 and 2 only1, 2 and then Loop endLoop end onlyThe loop ends normally, so else runs.
i = 1
while i <= 2:
print(i)
i += 1
else:
print("Loop end")1
2
Loop end- The condition
i <= 2becomes false after two rounds, so the loop ends normally andelseruns. - Answer: option 2.
Multiple Choice Question (MCQ): choose the one correct option.
What does the palindrome program print for the input 10?
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")PalindromeNot a palindrome10Reverse 10 as a number.
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")Enter a number: 10
Not a palindrome- 10 reversed is the number 1 (the leading zero vanishes), and
1 != 10. - Answer: option 2.
Numerical Answer Type (NAT).
What does the program print?
data = [-5, -2, -8]
best = 0
for v in data:
if v > best:
best = v
print(best)Starting from 0 assumes the data contains something at least as large as 0.
data = [-5, -2, -8]
best = 0
for v in data:
if v > best:
best = v
print(best)0- No value in the list is greater than
0, sobestnever changes and the program prints0, which is not even in the list. The correct start isbest = data[0], which gives-2. - Answer: 0
Numerical Answer Type (NAT).
What is printed?
a, b = 84, 36
while b != 0:
a, b = b, a % b
print(a)Trace the pair round by round.
a, b = 84, 36
while b != 0:
a, b = b, a % b
print(a)12- , since and . The loop stops with .
- Answer: 12
Numerical Answer Type (NAT).
What is the last number printed?
x, y = 0, 1
for _ in range(7):
print(x, end=" ")
x, y = y, x + yThe loop prints seven terms: each round prints x, then moves the pair along.
x, y = 0, 1
for _ in range(7):
print(x, end=" ")
x, y = y, x + y0 1 1 2 3 5 8 - The terms are . The seventh is
8. - Answer: 8
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
for n in [4, 5]:
for d in range(2, n):
if n % d == 0:
print(n, "composite")
break
else:
print(n, "prime")4 composite then 5 prime4 prime then 5 prime4 composite then 5 composite4 composite, 4 prime, 5 primeThe else belongs to the inner for, and runs only if that loop finished without a break.
for n in [4, 5]:
for d in range(2, n):
if n % d == 0:
print(n, "composite")
break
else:
print(n, "prime")4 composite
5 primen = 4:d = 2divides 4, so it prints4 compositeandbreaks; theelseis skipped.n = 5: nodin2, 3, 4divides 5, nobreak, soelseprints5 prime.- Answer: option 1.
Numerical Answer Type (NAT).
What does the program print?
data = [3, 6, 0, 10, 10]
total = 0
for v in data:
if v == 0:
break
total += v
print(total)break leaves the loop at the first 0; the numbers after it are never read.
data = [3, 6, 0, 10, 10]
total = 0
for v in data:
if v == 0:
break
total += v
print(total)9- . If
breakwerecontinue, the 0 would just be skipped and the answer would be . - Answer: 9
indented block
No update = infinite loop
False (not after break)
% 10 reads a digit
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.
for variable in sequence: followed by an indented block.
2.2Looping through a list and a string
pets = ["cats", "goats", "dogs"]
for pet in pets:
print(pet)cats
goats
dogstxt = "Hello"
for x in txt:
print(x)H
e
l
l
o2.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.
for x in range(5):
print(x)0
1
2
3
4start: the first value (default 0).stop: the end point plus 1; it is never included.step: the increment (default 1; negative to count down).
for x in range(3, 8, 2):
print(x)3
5
7for x in range(5, -1, -1):
print(x)5
4
3
2
1
010.| Call | Values | How 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
forwhen you know what to loop over; usewhilewhen you repeat until a condition changes. - The variable stays after the loop (extra). After
for x in range(3)the namexstill holds2. - Do not change the counter yourself. A
forloop updates its variable automatically; noi += 1is needed.
for x in range(3):
pass
print(x)22.5Exam tips and common mistakes
- Write the list of values
rangeproduces before reading the loop body. - Number of rounds of
range(start, stop, step)with a positive step is about(stop - start) / step, rounded up.
- 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-1step when counting down.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
for x in range(2, 10, 3):
print(x, end=" ")2 5 82 5 8 112 3 4 ... 103 6 9Start at 2, add 3, stop before 10.
for x in range(2, 10, 3):
print(x, end=" ")2 5 8 - The values are 2, 5, 8 (the next would be 11, which is not below 10).
- Answer: option 1.
Numerical Answer Type (NAT).
How many numbers does range(1, 10, 2) produce? The program prints the count.
print(len(range(1, 10, 2)))List them: 1, 3, 5, ...
print(len(range(1, 10, 2)))5- The values are 1, 3, 5, 7, 9: five numbers.
- Answer: 5
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
for x in range(10, 0, -3):
print(x, end=" ")10 7 4 110 7 4 1 -210 7 4The stop value 0 is never reached, and the step is -3.
for x in range(10, 0, -3):
print(x, end=" ")10 7 4 1 - 10, 7, 4, 1 are all above 0; the next, -2, is not.
- Answer: option 1.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
for x in range(5, 1):
print(x)
print("done")5 4 3 2done only5 then doneA positive step cannot go from 5 down to 1.
for x in range(5, 1):
print(x)
print("done")donerange(5, 1)is empty, so the loop body never runs and only the last line prints.- Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Which statements about the program are true?
for x in "Hello":
print(x)A string is a sequence of characters.
for x in "Hello":
print(x)H
e
l
l
o"Hello"has 5 characters, each printed on its own line.- Answer: options 1, 2 and 4.
Numerical Answer Type (NAT).
What is the last number printed?
last = 0
for x in range(0, 31, 3):
last = x
print(last)The stop value is never reached.
last = 0
for x in range(0, 31, 3):
last = x
print(last)30range(0, 31, 3)counts 0, 3, ..., 30; 33 would be past 31.- Answer: 30
visits each item
range(a, b, s): a to b-1
5 down to 0
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
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)Enter a no.: 5
Sum of first 5 numbers is 15| x | sum before | sum after |
|---|---|---|
| 1 | 0 | 1 |
| 2 | 1 | 3 |
| 3 | 3 | 6 |
| 4 | 6 | 10 |
| 5 | 10 | 15 |
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
for i in range(11):
print("2 x", i, "=", 2 * i)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 = 20range(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.
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")Enter a number: 7
Prime Number| Input | Output | Why |
|---|---|---|
| 7 | Prime Number | no divisor among 2..6 |
| 9 | Not a prime number | 3 divides 9 |
| 2 | Prime Number | the range 2..1 is empty, so flag stays True |
| 1 | Not a prime number | not greater than 1 |
| 0 | Not a prime number | not greater than 1 |
3.4Sum of all digits
x = int(input("Enter a number: "))
sum = 0
for i in str(x):
sum += int(i)
print("Sum of all digits is", sum)Enter a number: 1234
Sum of all digits is 10str(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
x = int(input("Enter a number: "))
for i in range(x):
if i % 3 == 0 or i % 5 == 0:
print(i)Enter a number: 16
0
3
5
6
9
10
12
153.6All factors of a number
x = int(input("Enter a no.: "))
for i in range(1, x + 1):
if x % i == 0:
print(i)Enter a no.: 12
1
2
3
4
6
12| Input | Factors |
|---|---|
| 12 | 1 2 3 4 6 12 |
| 7 | 1 7 |
| 1 | 1 |
| 36 | 1 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.
x = 29
flag = True
for i in range(2, x):
if x % i == 0:
flag = False
break
print("Prime" if flag else "Not prime")Prime3.8Exam tips and common mistakes
- 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.
- Using
range(1, n)for the sum of the firstnnumbers (it stops atn - 1). - Forgetting
int(i)when adding digit characters. - Treating 1 as prime.
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What does the sum program print for the input 10?
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)Add 1 through 10.
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)Enter a no.: 10
Sum of first 10 numbers is 551 + 2 + ... + 10 = 55.- Answer: 55
Multiple Choice Question (MCQ): choose the one correct option.
What does the prime program print for the input 15?
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")Prime NumberNot a prime numberDoes any number from 2 to 14 divide 15?
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")Enter a number: 15
Not a prime number- 3 and 5 divide 15, so the flag becomes
False. - Answer: option 2.
Numerical Answer Type (NAT).
What does the digit-sum program print for the input 9045?
x = int(input("Enter a number: "))
sum = 0
for i in str(x):
sum += int(i)
print("Sum of all digits is", sum)Add the four digits.
x = int(input("Enter a number: "))
sum = 0
for i in str(x):
sum += int(i)
print("Sum of all digits is", sum)Enter a number: 9045
Sum of all digits is 189 + 0 + 4 + 5 = 18.- Answer: 18
Multiple Choice Question (MCQ): choose the one correct option.
For the input 11, what is printed (one number per line)?
x = int(input("Enter a number: "))
for i in range(x):
if i % 3 == 0 or i % 5 == 0:
print(i)0 3 5 6 9 103 5 6 9 100 3 5 6 93 5 6 9 10 11range(11) starts at 0 and stops at 10.
x = int(input("Enter a number: "))
for i in range(x):
if i % 3 == 0 or i % 5 == 0:
print(i)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.
Numerical Answer Type (NAT).
How many lines does the factors program print for the input 36?
x = 36
count = 0
for i in range(1, x + 1):
if x % i == 0:
count += 1
print(count)Count the divisors of 36.
x = 36
count = 0
for i in range(1, x + 1):
if x % i == 0:
count += 1
print(count)9- The factors of 36 are 1, 2, 3, 4, 6, 9, 12, 18, 36: nine lines.
- Answer: 9
Multiple Choice Question (MCQ): choose the one correct option.
What does the prime program print for the input 2?
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")Prime NumberNot a prime numberIs 2 > 1? What does range(2, 2) give?
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")Enter a number: 2
Prime Number2 > 1is true,range(2, 2)is empty, soflagstaysTrue.- Answer: option 1.
sum += x
test 2 .. x-1
False on a divisor
int(i)
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.
animal = ["tiger", "cat", "dog"]
sounds = ["roars", "meows", "barks"]
for x in animal:
for y in sounds:
print(f"the {x} {y}")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 barksIf the outer loop runs m times and the inner loop runs n times each, the inner body runs m × n times in total.
count = 0
for i in range(3):
for j in range(4):
count += 1
print(count)124.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.
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=' ')Enter a no.: 20
2 3 5 7 11 13 17 19 | Input | Output |
|---|---|
| 20 | 2 3 5 7 11 13 17 19 |
| 12 | 2 3 5 7 11 |
| 3 | 2 |
| 2 | 2 |
| 1 | (nothing) |
2 the program prints 2, which is not below 2. Changing the first test to num > 2 fixes it.| Input | Original | Fixed (num > 2) |
|---|---|---|
| 2 | 2 | (nothing) |
| 3 | 2 | 2 |
| 10 | 2 3 5 7 | 2 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.
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: ')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| Trader | Trades | Result |
|---|---|---|
| 101 | 100, -30 | 70 |
| 102 | 50 | 50 |
4.4Problem 3: day-wise total rainfall
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}")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 5Here 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
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)Enter a word: tree
Enter a word: elephant
Enter a word: sun
Enter a word: -1
The length of the longest word is: 8The inner for counts the letters of each word; maxlen keeps the largest count seen. (A shorter way is len(word), extra.)
| Word | count | maxlen after |
|---|---|---|
| tree | 4 | 4 |
| elephant | 8 | 8 |
| sun | 3 | 8 |
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.
for i in range(1, 5):
for j in range(i):
print("*", end="")
print()*
**
***
****4.7Exam tips and common mistakes
- 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.
- Forgetting that
breakleaves only the inner loop. - Not resetting
totalorpro_lossfor each trader or day. - Forgetting to read the next value at the end of a sentinel loop (infinite loop).
Practice questions (graded-assignment style)
Numerical Answer Type (NAT).
What does the program print?
count = 0
for i in range(4):
for j in range(5):
count += 1
print(count)Multiply the two loop lengths.
count = 0
for i in range(4):
for j in range(5):
count += 1
print(count)20- The outer loop has 4 rounds and the inner loop has 5 rounds each: 4 × 5 = 20.
- Answer: 20
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
for i in range(1, 3):
for j in range(1, 3):
print(i, j)1 1 1 2 2 1 2 2 (pairs, in this order)1 1 2 1 1 2 2 21 2 2 12 2The inner loop finishes for each outer value.
for i in range(1, 3):
for j in range(1, 3):
print(i, j)1 1
1 2
2 1
2 2- For
i = 1:j = 1, 2; then fori = 2:j = 1, 2. - Answer: option 1.
Multiple Choice Question (MCQ): choose the one correct option.
What does the primes-below program print for the input 12?
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=' ')2 3 5 7 112 3 5 73 5 7 112 3 5 7 9 11Which numbers from 2 to 11 are prime?
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=' ')Enter a no.: 12
2 3 5 7 11 - 2, 3, 5, 7 and 11 are prime (11 is below 12).
- Answer: option 1.
Numerical Answer Type (NAT).
For trader 7 the trades are 20, 20, -5 and then 0. What profit/loss does the program print?
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: ')The 0 only stops the loop; it is not added.
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: ')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: -120 + 20 - 5 = 35.- Answer: 35
Numerical Answer Type (NAT).
For the words sky, python, is and then -1, what length is printed?
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)Compare the lengths 3, 6, 2.
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)Enter a word: sky
Enter a word: python
Enter a word: is
Enter a word: -1
The length of the longest word is: 6pythonhas 6 letters, the longest word.- Answer: 6
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
break1 1 only1 1 then 2 1 then 3 11 1, 1 2, 1 3break ends only the inner loop.
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
break1 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.
for each outer round
m × n rounds
while loop of inputs
inside the outer loop
fix for n = 2
keep the maximum
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.
num, i = 2, 1
print(num, "x", i, "=", num * i)2 x 1 = 25.2The string modulo operator (%)
num, i = 2, 1
print('%d x %d = %d' % (num, i, num * i))2 x 1 = 2| Specifier | Meaning | Example |
|---|---|---|
%d | integer | 7 |
%f | float (6 decimals by default) | 3.500000 |
%.2f | float with 2 decimals (extra) | 3.14 |
%s | string (extra) | hi |
The values after % go in a tuple, in the same order as the specifiers.
5.3The format() method
num, i = 2, 1
print('{0} x {1} = {2}'.format(num, i, num * i))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.
print('{1} {0} {1}'.format('a', 'b'))b a b5.4f-strings
num, i = 2, 1
print(f"{num} x {i} = {num * i}")2 x 1 = 2Put an f before the opening quote and write variables (even expressions such as num * i) directly inside {}.
num = 2
for i in range(1, 4):
print(f"{num} x {i} = {num * i}")2 x 1 = 2
2 x 2 = 4
2 x 3 = 65.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.
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}")Value of pi: 3.143
Value of pi = 3.14
Value of pi: 3.143Value 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.x = 1234.5678
print(f"{x:.2f}")
print(f"{x:.0f}")
print(f"{x:.1f}")1234.57
1235
1234.65.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.
print("Welcome to", end=" ")
print("Python", end=" ")
print("stuck", end="@")
print("home")Welcome to Python stuck@homeprint("G", "F", "E", sep="")
print("09", "12", "2016", sep="-")GFE
09-12-2016end=''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 butxitself is unchanged.
print(1, 2, 3, sep=", ")
x = 3.14159
print(f"{x:.2f}")
print(x)1, 2, 3
3.14
3.141595.8Exam tips and common mistakes
- Translate each format string into the final text by replacing placeholders one by one.
- For
:.nfcount n digits after the point and round the last one.
- Forgetting the
fbefore 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)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
print('{1} {0} {1}'.format('a', 'b'))b a ba b a0 1 0Positions count from 0: {1} is "b".
print('{1} {0} {1}'.format('a', 'b'))b a b{1}is the second argumentb,{0}the first,a.- Answer: option 1.
Numerical Answer Type (NAT).
What does the program print?
x = 1234.5678
print(f"{x:.2f}")Two decimals, rounded.
x = 1234.5678
print(f"{x:.2f}")1234.571234.5678rounded to 2 decimals is1234.57.- Answer: 1234.57
Multiple Select Question (MSQ): select all that apply.
Which of these print 3 x 4 = 12?
print('%d x %d = %d', 3, 4, 12)print('%d x %d = %d' % (3, 4, 12))print('{0} x {1} = {2}'.format(3, 4, 12))print(f"3 x 4 = {3 * 4}")print('%d x %d = %d', 3, 4, 12)Option 4 forgets the % operator.
print('%d x %d = %d', 3, 4, 12)%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.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
print("A", end="-")
print("B")A-B on one lineA and B on two linesAB on one lineA B on one lineend replaces the newline after the first print.
print("A", end="-")
print("B")A-B- The first print ends with
-instead of a newline, soBfollows on the same line. - Answer: option 1.
Numerical Answer Type (NAT).
What does the program print?
print("2026", "09", "18", sep="-")sep goes between the arguments.
print("2026", "09", "18", sep="-")2026-09-18- The three arguments are joined with
-between them. - Answer: 2026-09-18
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
x = 22/7
print(f"Value of pi: {x:.3f}")3.1413.1433.1423.1422/7 = 3.142857...; round to 3 decimals.
x = 22/7
print(f"Value of pi: {x:.3f}")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.
'{0}'.format(v)
f'{v}'
rounded
default newline
default space
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.
6.1break: leave the loop
break stops the current loop entirely; execution continues after the loop.
x = "Hello @ World"
for i in x:
if i == "@":
break
print(i, end="")Hello i = 1
while i <= 5:
if i == 3:
break
print(i)
i += 11
2The 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.
txt = "hello"
for x in txt:
if x == "l":
continue
print(x)h
e
owhile loop, put the counter update before continue, or the loop can stick forever on the same value.i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)1
2
4
56.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.
if 5 == 5:
pass
else:
pass
print("Hello World")Hello World| Statement | Effect | Code after it in the round |
|---|---|---|
break | leaves the whole loop | skipped |
continue | jumps to the next round | skipped |
pass | nothing | runs normally |
6.4Going deeper
- break and else (extra). A loop's
elseruns only if the loop was not left bybreak. That makes it a handy "not found" branch. - Nested loops (extra).
breakandcontinueaffect 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.
for n in range(2, 7):
for d in range(2, n):
if n % d == 0:
break
else:
print(n, "is prime")2 is prime
3 is prime
5 is prime6.5Exam tips and common mistakes
- 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.
- Mixing up
break(stop everything) andcontinue(skip one round). - Using
continuebefore the counter update in awhileloop. - Thinking
passskips the rest of the loop body.
Practice questions (graded-assignment style)
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
for i in range(1, 6):
if i == 3:
break
print(i, end=" ")1 21 2 31 2 4 53break ends the loop when i == 3.
for i in range(1, 6):
if i == 3:
break
print(i, end=" ")1 2 - The loop prints 1 and 2, and leaves at 3 before printing it.
- Answer: option 1.
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
for i in range(1, 6):
if i == 3:
continue
print(i, end=" ")1 2 4 51 21 2 3 4 53continue skips only the round for 3.
for i in range(1, 6):
if i == 3:
continue
print(i, end=" ")1 2 4 5 - When
i == 3the print is skipped, but rounds 4 and 5 still run. - Answer: option 1.
Numerical Answer Type (NAT).
What does the program print?
for i in range(1, 101):
if i % 7 == 0:
print(i)
breakThe loop stops at the first multiple of 7.
for i in range(1, 101):
if i % 7 == 0:
print(i)
break7range(1, 101)reaches 7 first, prints it andbreaks.- Answer: 7
Numerical Answer Type (NAT).
What does the program print?
count = 0
for i in range(1, 11):
if i % 3 == 0:
continue
count += 1
print(count)Count the numbers from 1 to 10 that are not multiples of 3.
count = 0
for i in range(1, 11):
if i % 3 == 0:
continue
count += 1
print(count)7- The multiples of 3 are 3, 6, 9, so 10 - 3 = 7 numbers are counted.
- Answer: 7
Multiple Choice Question (MCQ): choose the one correct option.
What does the program print?
for i in range(3):
pass0 1 2 on three linespasspass does nothing.
for i in range(3):
pass- The loop runs three times but each round only executes
pass, so nothing is printed. - Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
break ends the whole loopcontinue ends the whole loopcontinue skips the rest of the current roundpass skips the rest of the current roundRecall the table.
breakleaves the loop;continueskips to the next round.passdoes nothing and the rest of the round still runs.- Answer: options 1 and 3.
entirely
next round
does nothing
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.
Print all even numbers from 1 to 20 using a while loop.
Idea: Start at 2 and step by 2.
i = 2
while i <= 20:
print(i, end=" ")
i += 22 4 6 8 10 12 14 16 18 20 Print the numbers 1 to 5, then print Done once the loop ends.
Idea: else runs when the test turns false.
i = 1
while i <= 5:
print(i, end=" ")
i += 1
else:
print("Done")1 2 3 4 5 DoneLoop through the string "EngiKode" and print each character.
Idea: A string is iterable.
for ch in "EngiKode":
print(ch, end=" ")E n g i K o d e Print every 3rd number from 0 to 30 using range().
Idea: The stop value is 31 so 30 is included.
for x in range(0, 31, 3):
print(x, end=" ")0 3 6 9 12 15 18 21 24 27 30 Print a 5 × 5 grid of stars using nested for loops.
Idea: The inner loop prints a row; the empty print() ends it.
for i in range(5):
for j in range(5):
print("*", end="")
print()*****
*****
*****
*****
*****Print 3 x 4 = 12 using all three formatting methods.
Idea: All three give the same text.
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}")3 x 4 = 12
3 x 4 = 12
3 x 4 = 12Print 2026-09-18 from three separate values using sep.
Idea: sep joins the values with a dash.
print('2026', '09', '18', sep='-')2026-09-18Loop through 1 to 100 and stop as soon as you hit a number divisible by 7.
Idea: break after the first hit.
for i in range(1, 101):
if i % 7 == 0:
print(i)
break7Print the numbers 1 to 10, skipping multiples of 3.
Idea: continue jumps over the print for 3, 6, 9.
for i in range(1, 11):
if i % 3 == 0:
continue
print(i, end=" ")1 2 4 5 7 8 10 Write a program that finds all prime numbers between 1 and 50.
Idea: Test each number against the smaller ones; break at the first divisor.
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=" ")2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 end=" " to keep numbers on one line; printing one per line works equally well.7.1Exam tips and common mistakes
- 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.
- Starting
rangeat 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)
Multiple Choice Question (MCQ): choose the one correct option.
How many numbers does the Q1 program print?
i = 2
count = 0
while i <= 20:
count += 1
i += 2
print(count)List 2, 4, ..., 20.
i = 2
count = 0
while i <= 20:
count += 1
i += 2
print(count)10- The even numbers from 2 to 20 are ten numbers.
- Answer: option 2.
Numerical Answer Type (NAT).
How many * characters does the grid program print in total?
total = 0
for i in range(5):
for j in range(5):
total += 1
print(total)5 rows of 5.
total = 0
for i in range(5):
for j in range(5):
total += 1
print(total)25- 5 outer rounds × 5 inner rounds = 25 stars.
- Answer: 25
Numerical Answer Type (NAT).
How many prime numbers are there between 1 and 50?
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)Count the output of Q10.
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)15- The primes are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47: fifteen of them.
- Answer: 15
Multiple Choice Question (MCQ): choose the one correct option.
What is the sum of the numbers the Q9 program prints?
total = 0
for i in range(1, 11):
if i % 3 == 0:
continue
total += i
print(total)Add all of 1 to 10 and subtract the multiples of 3.
total = 0
for i in range(1, 11):
if i % 3 == 0:
continue
total += i
print(total)3755 - (3 + 6 + 9) = 37.- Answer: option 2.
while ... else
formatting, sep
primes to 50
Week 3 Summary Sheet
One page to revise all of Week 3: loops, formatting, loop control and the exam checklist.
The big picture
- Repeats while the test is True; update the counter.
elseruns when the loop ends normally.
forvisits each item of a sequence.range(start, stop, step); stop excluded.
- Sum, table, prime, digit sum, factors.
- Flag pattern: assume True, set False.
- Inner loop runs fully per outer round.
- Sentinel input loops; reset inner totals.
%d %f,format(), f-strings,:.nf.endandsepinprint.
breakstops the loop.continueskips a round;passdoes nothing.
- Ten tasks with real outputs.
- Primes up to 50: fifteen of them.
Revision sheet
| Topic | Key point |
|---|---|
| while | runs while a condition is True |
| while...else | else runs once the loop ends normally |
| for | iterates over a sequence / iterable |
| range(n) | 0 to n-1 |
range(a, b, step) | a to b-1, stepping by step |
| Reverse range | range(5, -1, -1) gives 5 down to 0 |
| Nested loops | a loop placed inside another loop |
%d %f | modulo-style format specifiers |
.format() | {0} {1} {2} positional placeholders |
| f-strings | variables directly inside {} |
{x:.2f} | decimal-place format specifier |
end='' | changes what print() ends a line with |
sep='' | changes the separator between print() arguments |
break | stops the loop entirely |
| continue | skips to the next iteration |
| pass | does nothing; syntactic placeholder |
Which loop when?
| Situation | Use |
|---|---|
| repeat a fixed number of times | for i in range(n) |
| go through every item or character | for x in sequence |
| repeat until something changes or input ends | while |
| stop at the first match | break |
| ignore some items | continue |
| leave a block empty for now | pass |
Exam checklist (from the source)
whileloop syntax and counter increments.while...else.forloop 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.
endandsepparameters.breakversuscontinue.passas a placeholder.
Common mistakes
- A
whilewithout an update runs forever.
- The stop value is never included.
- Set running totals to 0 inside the outer loop.
breakleaves the loop;continueskips one round.
- Without the
fthe braces print literally.
- 22/7 to 3 places is 3.143, not 3.141.