Start with the study notes on Loops (definitions, examples and a quick revision), then work through 30 practice questions, each with the correct answer and a clear explanation of why it is right. When you are ready, take this topic as an interactive quiz to test yourself.
12 easy Β· 13 medium Β· 5 hard Β· Part of Python: Master Python from basics to advanced - 20 topics.
Topic overview
Loops β repeating work with for and while
1. The for loop and range()
A for loop runs once for each item in an iterable (a list, string, rangeβ¦). range(start, stop, step) produces numbers up to, but not including, stop.
for i in range(3):
print(i)
print(list(range(2, 10, 2)))
print(list(range(5, 0, -1))) # counting down
Output0
1
2
[2, 4, 6, 8]
[5, 4, 3, 2, 1]
Looping over strings and lists
for ch in "abc":
print(ch, end=" ")
print()
for fruit in ["apple", "mango"]:
print(fruit)
Outputa b c
apple
mango
2. The while loop
A while loop repeats as long as its condition is true. You must change something inside the loop, or it never stops (an infinite loop; press Ctrl+C to stop it).
i = 1
while i <= 3:
print(i)
i += 1 # without this the loop runs forever
Output1
2
3
Remember: Use for when you know what to loop over, and while when you only know when to stop.
3. break, continue and pass
breakexits the loop immediately.
continueskips the rest of this round and goes to the next one.
pass does nothing at all.
for n in [3, 7, 12, 5]:
if n > 10:
break
print(n)
for i in range(5):
if i == 2:
continue
print(i, end=" ")
Output3
7
0 1 3 4
4. Common loop patterns
A. Running total (accumulator)
total = 0
for i in range(1, 5):
total += i
print(total)
Output10
B. Counting matches
count = 0
for ch in "banana":
if ch in "aeiou":
count += 1
print(count)
Output3
C. Nested loops
The inner loop runs fully for each round of the outer loop, so the counts multiply.
for i in range(1, 4):
print("*" * i)
Output*
**
***
5. enumerate(), zip() and reversed()
enumerate() gives the index and the item together.
zip() walks several lists side by side, stopping at the shortest.
reversed() loops backwards without changing the list.
for i, fruit in enumerate(["apple", "mango"], start=1):
print(i, fruit)
for name, mark in zip(["Ana", "Ben"], [90, 85]):
print(name, mark)
print(list(reversed([1, 2, 3])))
Output1 apple
2 mango
Ana 90
Ben 85
[3, 2, 1]
6. The loop else clause
A loop's else block runs only if the loop finished without a break. It is perfect for searches.
for n in [1, 3, 5]:
if n == 4:
print("found")
break
else:
print("not found")
Outputnot found
7. Loops that run at least once
Python has no do-while loop. Use while True: with a break.
while True:
choice = input("Command (q to quit): ")
if choice == "q":
break
print("You chose", choice)
8. Two traps
Don't remove items from a list while looping over it: items shift and get skipped. Loop over a copy (nums[:]) or build a new list.
The loop variable survives after a for loop, holding its last value.
nums = [1, -2, -3, 4]
nums = [x for x in nums if x >= 0] # safe filtering
print(nums)
for i in range(3):
pass
print(i)
Output[1, 4]
2
9. Common misconceptions
Misconception
Correct understanding
range(5) includes 5.
range(5) gives 0 to 4; the stop value is excluded.
break exits all nested loops.
break exits only the innermost loop.
continue and pass do the same thing.
continue skips to the next round; pass does nothing and the code below still runs.
A loop's else runs when the loop condition is false at the start.
It runs when the loop ends without a break.
You can loop over a number: for i in 5.
An int is not iterable; use range(5).
10. Quick revision
for loop
Repeats once per item in an iterable.
range()
Numbers from start up to (not including) stop.
while loop
Repeats while a condition is true.
break
Leaves the loop.
continue
Skips to the next round.
enumerate()
Gives index and item together.
zip()
Loops over several sequences side by side.
Loop else
Runs if the loop ended without break.
11. Test your understanding
How many times does for i in range(5) run?
Show answer
5 times (0 to 4).
What does list(range(2, 10, 2)) give?
Show answer
[2, 4, 6, 8]
What most often causes an infinite while loop?
Show answer
Forgetting to update the loop variable.
What does continue do?
Show answer
Skips the rest of this round and starts the next one.
How many stars does a 3 Γ 2 nested loop print (one per inner round)?
Show answer
6
What does enumerate() give you?
Show answer
The index and the item.
When does a loop's else block run?
Show answer
When the loop finishes without break.
How do you stop a program stuck in an infinite loop?
Show answer
Press Ctrl+C.
Key takeaway: Use for to go through items and while to repeat until a condition changes; break leaves, continue skips, and enumerate/zip keep loops clean.
Notes written by Velnov. Every code example with an output was run in Python 3 to check that the output shown is exactly what Python prints.
range(start, stop, step): begin at 2, jump by 2, stop BEFORE 10 - giving 2, 4, 6, 8. The stop value is always excluded.
range()Step
Q3.easy
What does the break statement do inside a loop?
for n in [3, 7, 12, 5]:
if n > 10:
break # stop at 12
print(n) # 3 7
print("done")
A Skips one iteration
B Exits the loop immediately
C Pauses the loop
D Restarts the loop
Answer: B β Exits the loop immediately
break terminates the loop at once - execution jumps to the first line AFTER the loop. Used to stop early when you've found what you need.
continueLoop control
Q5.easy
Which is the correct while loop that counts 1 to 3?
i = 1
while i <= 3:
print(i)
i += 1 # without this: infinite loop!
A i = 1\nwhile i <= 3:\n print(i)\n i += 1
B while i <= 3:\n print(i)
C while (i = 1; i <= 3; i++):\n print(i)
D while i in range(3): print(i)
Answer: A β i = 1\nwhile i <= 3:\n print(i)\n i += 1
A while loop needs: the variable created BEFORE the loop, a condition, and an update INSIDE the loop. Option B never defines or updates i; option C is C-language syntax.
whileInfinite loops
Q6.easy
What causes an INFINITE loop most often?
i = 0
while i < 5:
print(i)
# forgot i += 1 -> prints 0 forever!
A Using range() with big numbers
B Forgetting to update the loop variable inside a while loop
C Using break
D Nesting loops
Answer: B β Forgetting to update the loop variable inside a while loop
If the while condition never becomes False - typically because you forgot i += 1 - the loop runs forever. Press Ctrl+C to stop a runaway program.
whileCtrl+C
Q7.easy
What is the output of:
for ch in "abc":
print(ch)
for ch in "abc":
print(ch)
# a
# b
# c
A abc
B a b c (each on its own line)
C 0 1 2
D Error
Answer: B β a b c (each on its own line)
A for loop over a string visits each CHARACTER in order: 'a', then 'b', then 'c' - each printed on its own line. Strings are iterable.
IterablesStrings
Q8.easy
What is the output of:
total = 0
for i in range(3):
total += i
print(total)
total = 0
for i in range(3):
total += i # 0, then 1, then 3
print(total) # 3
A 3
B 6
C 0
D 2
Answer: A β 3
range(3) gives 0, 1, 2. The accumulator adds them: 0 + 0 + 1 + 2 = 3. This 'running total' pattern is one of the most common loop uses.
Accumulator patternsum()
Q12.easy
What happens with:
for i in range(0):
print("hello")
A Prints hello once
B Prints hello forever
C The body never runs - no output
D Error
Answer: C β The body never runs - no output
range(0) is empty, so the loop body executes zero times. No error - the program just moves on. Same happens looping over an empty list.
range()Empty iterables
Q16.easy
What does the underscore mean in:
for _ in range(3):
print("hi")
for _ in range(3):
print("hi") # hi hi hi
A It's a syntax error
B A throwaway variable name - we don't need the loop value
C It makes the loop private
D It repeats twice as fast
Answer: B β A throwaway variable name - we don't need the loop value
_ is a normal variable name that conventionally signals 'I'm not going to use this value'. Here we only care about repeating 3 times, not about the counter.
Conventionsrange()
Q23.easy
Which loop is better for 'do something for EACH item in a list'?
for item in cart: # natural
print(item)
while balance > 0: # condition-driven
balance -= withdraw()
A for - it's made for iterating over collections
B while - it's more powerful
C Both are equally idiomatic
D Neither - use recursion
Answer: A β for - it's made for iterating over collections
Rule of thumb: for when you know WHAT to iterate over (a list, string, range); while when you only know the STOPPING CONDITION (e.g. 'until the user quits').
for vs while
Q26.easy
What is the last number printed?
for i in range(1, 5):
print(i)
A 5
B 4
C 1
D 0
Answer: B β 4
range(1, 5) produces 1, 2, 3, 4 - it starts AT 1 and stops BEFORE 5. The last printed value is 4.
range()Off-by-one errors
Q29.easy
How do you stop a program stuck in an infinite loop in the terminal?
A Press Ctrl+C
B Type 'stop'
C Press Enter
D Close your eyes
Answer: A β Press Ctrl+C
Ctrl+C sends a KeyboardInterrupt, which stops the running Python program. Every programmer needs this shortcut on day one of learning while loops!
KeyboardInterruptInfinite loops
Medium questions (13)
Q4.medium
What does the continue statement do inside a loop?
for i in range(5):
if i == 2:
continue # skip printing 2
print(i) # 0 1 3 4
A Exits the loop entirely
B Skips the rest of the current iteration and moves to the next one
C Restarts the loop from the beginning
D Does nothing
Answer: B β Skips the rest of the current iteration and moves to the next one
continue jumps straight to the next iteration, skipping any remaining statements in the loop body this time around. break, by contrast, exits the loop completely.
breakLoop control
Q9.medium
How many stars does this print?
for i in range(3):
for j in range(2):
print("*")
for i in range(3): # 3 times
for j in range(2): # 2 times each
print("*") # 6 total
A 5
B 6
C 3
D 9
Answer: B β 6
The inner loop runs completely (2 times) for EACH of the 3 outer iterations: 3 x 2 = 6 stars. Nested loop counts always multiply.
Nested loops
Q10.medium
What does enumerate() give you in:
for i, fruit in enumerate(["apple", "mango"]):
for i, fruit in enumerate(["apple", "mango"]):
print(i, fruit)
# 0 apple
# 1 mango
A Only the values
B Only the indexes
C Both the index AND the value of each item
D The list sorted
Answer: C β Both the index AND the value of each item
enumerate() pairs each item with its position: (0, 'apple'), (1, 'mango'). It's the Pythonic replacement for range(len(list)) when you need both index and value.
enumerate(items, start=1) begins counting at 1.
enumerate()Unpacking
Q11.medium
Which range counts DOWN from 10 to 1?
for i in range(10, 0, -1):
print(i) # 10 9 8 ... 1
print("Liftoff!")
A range(10, 0, -1)
B range(10, 1)
C range(1, 10, -1)
D range(-10)
Answer: A β range(10, 0, -1)
A negative step walks backwards: range(10, 0, -1) gives 10, 9, 8, ... 1 (stop 0 excluded). Option C produces nothing - you can't go from 1 down to 10.
range()Negative step
Q13.medium
How many times does this while loop run?
x = 0
while x < 10:
x += 3
x = 0
count = 0
while x < 10:
x += 3
count += 1
print(count) # 4 (x: 3, 6, 9, 12)
A 3
B 4
C 10
D Infinite
Answer: B β 4
x takes the values 0, 3, 6, 9 (each < 10, so the body runs) and then 12, which fails the check. That's 4 iterations.
whileTracing code
Q15.medium
In a NESTED loop, what does break exit?
for i in range(3):
for j in range(3):
if j == 1:
break # exits inner only
print(i) # still prints 0 1 2
A All loops at once
B Only the innermost loop containing it
C The outermost loop
D The whole program
Answer: B β Only the innermost loop containing it
break only exits the single loop it lives in - the outer loop continues. To exit multiple levels, use a flag variable, return from a function, or restructure the code.
Nested loopsbreak
Q17.medium
What is the standard pattern for a loop that must run AT LEAST once (like a menu)?
while True:
choice = input("Command (q to quit): ")
if choice == "q":
break
print("You chose", choice)
A while True: ... with break when done
B do { } while - Python's do-while loop
C for ever:
D repeat until done:
Answer: A β while True: ... with break when done
Python has NO do-while loop. The idiom is while True: with a break when the exit condition is met - the body always runs at least once.
while TrueMenus
Q18.medium
What happens with:
for i in 5:
print(i)
# for i in 5: # TypeError!
for i in range(5): # correct
print(i)
A Prints 0 to 4
B Prints 5
C TypeError - int is not iterable
D Prints 1 to 5
Answer: C β TypeError - int is not iterable
You can't loop over a bare number - for needs an ITERABLE (range, list, string...). The fix: for i in range(5).
IterablesTypeError
Q19.medium
What is the difference between continue and pass?
for i in range(3):
if i == 1:
continue
print(i) # 0 2 (1 skipped)
for i in range(3):
if i == 1:
pass
print(i) # 0 1 2 (nothing skipped)
A They are identical
B continue skips to the next iteration; pass does nothing and execution continues to the next line
C pass skips the iteration; continue does nothing
D pass exits the loop
Answer: B β continue skips to the next iteration; pass does nothing and execution continues to the next line
continue actively jumps to the next iteration - lines after it don't run. pass is a no-op placeholder - lines after it DO run normally.
continuepass
Q20.medium
What does reversed() do in:
for x in reversed([1, 2, 3]):
print(x)
nums = [1, 2, 3]
for x in reversed(nums):
print(x) # 3 2 1
print(nums) # [1, 2, 3] - unchanged
A Prints 3 2 1
B Prints 1 2 3
C Reverses the list permanently
D Error
Answer: A β Prints 3 2 1
reversed() iterates the sequence back to front WITHOUT changing the original list. (list.reverse() is the method that permanently reverses in place.)
reversed()Slicing [::-1]
Q24.medium
Count the vowels: what is the output?
count = 0
for ch in "banana":
if ch in "aeiou":
count += 1
print(count)
count = 0
for ch in "banana":
if ch in "aeiou":
count += 1
print(count) # 3
A 2
B 3
C 6
D 0
Answer: B β 3
'banana' contains a, a, a - three vowels. The pattern: loop over characters, test membership with in, count matches.
Counting patternin operator
Q25.medium
Which is the more Pythonic way to loop over a list's values?
for item in items: # best
for i, item in enumerate(items): # need index too
for i in range(len(items)): # only to assign items[i] = ...
A for item in items:
B for i in range(len(items)): ... items[i]
C while i < len(items): ... items[i]
D All equally preferred
Answer: A β for item in items:
Iterate directly over the items - it's shorter, faster and can't have index bugs. Use range(len()) only when you must MODIFY items by index, and enumerate() when you need index AND value.
enumerate()Pythonic style
Q27.medium
What is the output?
for i in range(3):
print("*" * (i + 1))
for i in range(3):
print("*" * (i + 1))
# *
# **
# ***
A *\n**\n*** (a triangle)
B *** three times
C * three times
D Error
Answer: A β *\n**\n*** (a triangle)
i takes 0, 1, 2, so it prints 1, 2, then 3 stars - a growing triangle. String repetition inside a loop is the classic pattern-printing technique.
Pattern printingString repetition
Hard questions (5)
Q14.hard
What is the loop-else clause?
for n in nums:
if n == target: break
else:
print("not found")
for n in [1, 3, 5]:
if n == 4:
print("found")
break
else:
print("not found") # runs - no break happened
A It runs after every iteration
B It runs only when the loop finished WITHOUT hitting break
C It's a syntax error - else can't follow for
D It runs only when break happened
Answer: B β It runs only when the loop finished WITHOUT hitting break
Python's unusual for-else: the else block runs when the loop completes normally (no break). Perfect for search loops - if break never fired, the item wasn't found.
Think of else here as 'no-break'.
for-elseSearch patterns
Q21.hard
What does zip() do in:
for name, mark in zip(["Ana", "Ben"], [90, 85]):
names = ["Ana", "Ben"]
marks = [90, 85]
for name, mark in zip(names, marks):
print(name, mark)
# Ana 90
# Ben 85
A Compresses the lists to save memory
B Pairs items position-by-position: ("Ana", 90), then ("Ben", 85)
C Joins the lists into one long list
D Sorts both lists
Answer: B β Pairs items position-by-position: ("Ana", 90), then ("Ben", 85)
zip() walks multiple sequences in parallel, yielding tuples of matching positions. It stops at the SHORTEST sequence.
zip()Parallel iteration
Q22.hard
What is the output?
for i in range(3):
i = 100
print(i)
for i in range(3):
i = 100 # overwritten next iteration
print(i) # 100 100 100
print(i) # 100 (last value assigned)
A 100
B 2
C 102
D Error
Answer: A β 100
Tricky! Reassigning i inside the body doesn't affect the iteration - each pass, the for loop reassigns i to the NEXT range value. After the final pass, i was set to 100 by the body, so print shows 100.
The loop still runs exactly 3 times - you can't skip ahead by changing i.
Loop variablesTracing code
Q28.hard
Why is modifying a list WHILE looping over it dangerous?
for x in nums:
if x < 0: nums.remove(x)
nums = [1, -2, -3, 4]
for x in nums[:]: # loop over a copy
if x < 0:
nums.remove(x)
# or better:
nums = [x for x in nums if x >= 0]
A It's perfectly safe
B Removing items shifts positions, so the loop SKIPS elements
C It raises SyntaxError
D The list becomes immutable during loops
Answer: B β Removing items shifts positions, so the loop SKIPS elements
When you remove an item, everything after it shifts left - but the loop's internal position still advances, silently skipping the next element. Loop over a COPY (nums[:]) or build a new filtered list instead.
A very common source of 'why did it skip one?' bugs.
List mutationCopies
Q30.hard
What is the output?
n = 1
while n < 100:
n *= 2
print(n)
n = 1
while n < 100:
n *= 2
print(n) # 128
A 64
B 100
C 128
D Infinite loop
Answer: C β 128
n doubles: 1, 2, 4, 8, 16, 32, 64 (still < 100, so doubles again) -> 128, which fails the check. The loop exits with n = 128 - the first power of 2 that is >= 100.