for Loop & range()A loop repeats a block of code several times. The for loop is the simplest — it walks over a sequence of values, one at a time.
for variable in sequence: # indented block runs once per item statement
range() functionrange() produces a stream of numbers without storing them all in memory. It has three forms:
| Form | Produces |
|---|---|
range(n) | 0, 1, 2, …, n−1 |
range(a, b) | a, a+1, …, b−1 |
range(a, b, s) | a, a+s, a+2s, … (stops before b) |
for i in range(1, 6): print(i, i*i)Output:
1 1 / 2 4 / 3 9 / 4 16 / 5 25A for loop can also walk through any string, list, or tuple:
for ch in "Python": print(ch, end=" ")Output:
P y t h o nrange(a, b) never includes b. To go from 1 to 10 inclusive, write range(1, 11). To count down, use a negative step: range(10, 0, -1).while LoopA while loop repeats as long as a condition stays True. It is used when you don't know in advance how many rounds are needed.
while condition: # body runs as long as condition is True update_the_variable
n = 5 while n > 0: print(n, end=" ") n -= 1Output:
5 4 3 2 1num, total = 1234, 0 while num > 0: total += num % 10 num //= 10 print(total) # 10
while needswhile header.Ctrl + C to stop a runaway program.for ↔ while — When & ConversionBoth loops can do the same job, but each fits some problems better than the other.
Use for when… | Use while when… |
|---|---|
| The number of rounds is known. | You stop when something changes. |
| You walk through a list / string. | You wait for a user signal. |
| Counting up or down a range. | Reading input until a sentinel value. |
# for version for i in range(1, 6): print(i) # while version i = 1 while i <= 5: print(i) i += 1The
for form is shorter; the while form makes the counter changes visible.for → while)while condition.while, look at it again and ask: "Could a for with range() say the same thing in one line?" If yes, prefer the for — it is harder to mess up.break, continue and the loop elseThree small keywords change how a loop behaves once it has started.
break — quit the loop earlyfor n in range(20, 50): if n % 7 == 0: print("Found", n) breakOutput:
Found 21 — the loop stops immediately, even though numbers 22 to 49 remain.continue — skip this round, keep loopingfor i in range(1, 9): if i % 2 == 0: continue print(i, end=" ")Output:
1 3 5 7else clauseA for or while loop can have an else. It runs when the loop ends normally (without a break).
for n in range(2, 10): if n == 5: break else: print("never broke")Nothing prints — the
break ran. Without the if, "never broke" would print.break jumps out completely; continue only skips the current round. The loop else is unusual — remember it triggers only when no break happened.A loop placed inside another loop. The inner loop runs in full for every single round of the outer loop.
If the outer loop runs m times and the inner runs n times, the inner body runs m × n times.
for r in range(3): for c in range(4): print((r, c), end=" ") print()12 pairs are printed in 3 rows.
for i in range(1, 5): for j in range(i): print("*", end="") print()Output:
*
**
***
****break inside a nested loop only exits the inner loop. The outer loop keeps running. Use a boolean flag if you need to escape both.The chapter ends with a handful of standard loop programs every student must know by heart. The patterns repeat in many other problems.
n = int(input("n: ")) total = 0 for i in range(1, n + 1): total += i print(total)
nn = 5 fact = 1 for i in range(1, n + 1): fact *= i print(fact) # 120
n terms)n = 7 a, b = 0, 1 for _ in range(n): print(a, end=" ") a, b = b, a + bOutput:
0 1 1 2 3 5 8n = 17 prime = True for d in range(2, n): if n % d == 0: prime = False break print("Prime" if prime else "Not prime")
total = 0 for a sum, fact = 1 for a product. Initialising inside the loop resets it every round and gives the wrong answer.range(2, 10, 3) produces:
for i in range(3): print(i, end="")
break inside a loop causes:
continue inside a loop causes:
for i in range(2): for j in range(3): print("x")
else block runs when:
while loop usually happens because:
for ch in "AI":, the variable ch takes the values:
for i in range(1, 5): print(i*i, end=" ")Output:
n = 4 while n > 0: print(n, end=" ") n -= 1Output:
t = 0 for i in range(1, 6): t += i print(t)Output:
for i in range(1, 10): if i == 5: break print(i, end="")Output:
for i in range(1, 7): if i % 2 == 0: continue print(i, end="")Output:
for r in range(1, 4): for c in range(r): print("*", end="") print()Output:
a, b = 0, 1 for _ in range(5): print(a, end=" ") a, b = b, a + bOutput:
k = 1 while k < 50: k *= 3 print(k)Output:
Each snippet has exactly one error. Mark the line number and write the corrected line.
1 for i in range(5) 2 print(i)Wrong line: Correction:
1 for i in range(5): 2 print(i)Wrong line: Correction:
1 n = 5 2 while n > 0: 3 print(n)Wrong line: Correction:
1 for i in range(1, 5): 2 print(i) 3 print("end")Wrong line: Correction:
1 for i in range(10, 1): 2 print(i)Wrong line: Correction:
1 i = 0 2 while i < 5 3 print(i) 4 i += 1Wrong line: Correction:
for and while with one example each.
break and continue? Give one example of each.
while loop needs (initialise, test, update). Show an example with all three labelled.
for loop into an equivalent while loop:for i in range(2, 11, 2): print(i)
else clause of a loop do? Write one example where it runs and one where it does not.
print run in a nested loop where the outer goes 1 to 5 and the inner goes 1 to 4? Show your working.
Each program should read input from the user (where required) and produce a clear output. Use a separate sheet if you need more space.
n and print the sum of the first n natural numbers using a for loop with range().
n and print its factorial using a while loop. Reject n < 0 with a clear message.
5 x 1 = 5, …, 5 x 10 = 50. Use a for loop.
n and print a right-angled star triangle of height n:**********n and decide whether it is prime. Use a for loop with break; print "Prime" or "Not prime".