πŸŽ“ Velnov

🐍 Python · Topic 6 of 20

Loops β€” Python Questions with Answers

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

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

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

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

MisconceptionCorrect 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

  1. How many times does for i in range(5) run?

    Show answer

    5 times (0 to 4).

  2. What does list(range(2, 10, 2)) give?

    Show answer

    [2, 4, 6, 8]

  3. What most often causes an infinite while loop?

    Show answer

    Forgetting to update the loop variable.

  4. What does continue do?

    Show answer

    Skips the rest of this round and starts the next one.

  5. How many stars does a 3 Γ— 2 nested loop print (one per inner round)?

    Show answer

    6

  6. What does enumerate() give you?

    Show answer

    The index and the item.

  7. When does a loop's else block run?

    Show answer

    When the loop finishes without break.

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

Key concepts in this topic

range()IterationStepcontinueLoop controlbreakwhileInfinite loopsCtrl+CIterablesStringsAccumulator patternsum()Nested loopsenumerate()UnpackingNegative stepEmpty iterablesTracing codefor-elseSearch patternsConventionswhile TrueMenus

Jump to: Easy Β· Medium Β· Hard

Easy questions (12)

Q1. easy

How many times does this loop run? for i in range(5): print(i)

for i in range(5):
    print(i)   # 0 1 2 3 4
  1. A 4
  2. B 5
  3. C 6
  4. D Infinite

Answer: B β€” 5

range(5) generates 0, 1, 2, 3, 4 - five values, so the body runs 5 times. The stop value (5) is never included.

range()Iteration

Q2. easy

What values does range(2, 10, 2) produce?

print(list(range(2, 10, 2)))   # [2, 4, 6, 8]
print(list(range(1, 6)))        # [1, 2, 3, 4, 5]
  1. A 2, 4, 6, 8, 10
  2. B 2, 4, 6, 8
  3. C 4, 6, 8, 10
  4. D 2, 10, 2

Answer: B β€” 2, 4, 6, 8

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")
  1. A Skips one iteration
  2. B Exits the loop immediately
  3. C Pauses the loop
  4. 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!
  1. A i = 1\nwhile i <= 3:\n print(i)\n i += 1
  2. B while i <= 3:\n print(i)
  3. C while (i = 1; i <= 3; i++):\n print(i)
  4. 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!
  1. A Using range() with big numbers
  2. B Forgetting to update the loop variable inside a while loop
  3. C Using break
  4. 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
  1. A abc
  2. B a b c (each on its own line)
  3. C 0 1 2
  4. 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
  1. A 3
  2. B 6
  3. C 0
  4. 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")

  1. A Prints hello once
  2. B Prints hello forever
  3. C The body never runs - no output
  4. 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
  1. A It's a syntax error
  2. B A throwaway variable name - we don't need the loop value
  3. C It makes the loop private
  4. 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()
  1. A for - it's made for iterating over collections
  2. B while - it's more powerful
  3. C Both are equally idiomatic
  4. 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)

  1. A 5
  2. B 4
  3. C 1
  4. 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?

  1. A Press Ctrl+C
  2. B Type 'stop'
  3. C Press Enter
  4. 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
  1. A Exits the loop entirely
  2. B Skips the rest of the current iteration and moves to the next one
  3. C Restarts the loop from the beginning
  4. 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
  1. A 5
  2. B 6
  3. C 3
  4. 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
  1. A Only the values
  2. B Only the indexes
  3. C Both the index AND the value of each item
  4. 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!")
  1. A range(10, 0, -1)
  2. B range(10, 1)
  3. C range(1, 10, -1)
  4. 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)
  1. A 3
  2. B 4
  3. C 10
  4. 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
  1. A All loops at once
  2. B Only the innermost loop containing it
  3. C The outermost loop
  4. 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)
  1. A while True: ... with break when done
  2. B do { } while - Python's do-while loop
  3. C for ever:
  4. 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)
  1. A Prints 0 to 4
  2. B Prints 5
  3. C TypeError - int is not iterable
  4. 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)
  1. A They are identical
  2. B continue skips to the next iteration; pass does nothing and execution continues to the next line
  3. C pass skips the iteration; continue does nothing
  4. 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
  1. A Prints 3 2 1
  2. B Prints 1 2 3
  3. C Reverses the list permanently
  4. 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
  1. A 2
  2. B 3
  3. C 6
  4. 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] = ...
  1. A for item in items:
  2. B for i in range(len(items)): ... items[i]
  3. C while i < len(items): ... items[i]
  4. 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))
# *
# **
# ***
  1. A *\n**\n*** (a triangle)
  2. B *** three times
  3. C * three times
  4. 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
  1. A It runs after every iteration
  2. B It runs only when the loop finished WITHOUT hitting break
  3. C It's a syntax error - else can't follow for
  4. 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
  1. A Compresses the lists to save memory
  2. B Pairs items position-by-position: ("Ana", 90), then ("Ben", 85)
  3. C Joins the lists into one long list
  4. 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)
  1. A 100
  2. B 2
  3. C 102
  4. 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]
  1. A It's perfectly safe
  2. B Removing items shifts positions, so the loop SKIPS elements
  3. C It raises SyntaxError
  4. 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
  1. A 64
  2. B 100
  3. C 128
  4. 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.

whileTracing codePowers of 2

Practice β€œLoops” as a quiz