Editor

Python loops MCQ questions with answers

for, while, range, break and continue: count the passes before you check.

0 of 20 answered

  1. Question 1 · Easy

    What is the output of this code?

    for i in range(1, 10, 3):
        print(i, end=" ")
    Show the answer

    Answer: B

    range(1, 10, 3) starts at 1 and adds 3 each time while the value stays below 10: 1, 4, 7. The next value, 10, is not included because the stop value is never part of a range.

    Run this code in the editor
  2. Question 2 · Easy

    What is the output of this code?

    for i in range(10, 0, -3):
        print(i, end=" ")
    Show the answer

    Answer: C

    With a negative step, range counts down from the start and stops before passing the stop value: 10, 7, 4, 1. The next value, -2, would be past 0, so the loop ends.

    Run this code in the editor
  3. Question 3 · Medium

    What is the output of this code?

    print(list(range(5, 1)))
    print(list(range(-1, -5, -1)))
    Show the answer

    Answer: A

    range(5, 1) uses the default step of +1, and counting up from 5 never gets below 1, so it is empty. range(-1, -5, -1) counts down from -1 and stops before -5.

    Run this code in the editor
  4. Question 4 · Easy

    What is the output of this code?

    n = 1
    while n < 20:
        n = n * 3
    print(n)
    Show the answer

    Answer: D

    The loop multiplies by 3 while n < 20: 1 becomes 3, then 9, then 27. The condition is checked only at the start of each pass, so n ends at 27, the first value that is not below 20.

    Run this code in the editor
  5. Question 5 · Medium

    What is the output of this code?

    for n in range(1, 10):
        if n % 3 == 0:
            continue
        if n == 8:
            break
        print(n, end=" ")
    Show the answer

    Answer: C

    continue skips the rest of the current pass, so multiples of 3 are not printed. break ends the whole loop as soon as n is 8, before 8 is printed.

    Run this code in the editor
  6. Question 6 · Medium

    What is the output of this code?

    for nums in ([3, 5, 8, 9], [1, 7]):
        for n in nums:
            if n % 2 == 0:
                print("even:", n)
                break
        else:
            print("all odd")
    Show the answer

    Answer: B

    The else belongs to the inner for loop, not to the if. It runs only when that loop ends without break: the first list breaks at 8, so its else is skipped; the second list has no even number, so all odd is printed once.

    Run this code in the editor
  7. Question 7 · Easy

    What is the output of this code?

    for i in range(1, 4):
        for j in range(i):
            print("*", end="")
        print()
    Show the answer

    Answer: A

    The inner loop runs i times, printing stars on one line, and print() then ends the line. i takes the values 1, 2 and 3, giving rows of 1, 2 and 3 stars.

    Run this code in the editor
  8. Question 8 · Hard

    What is the output of this code?

    for i in range(3):
        for j in range(3):
            if j == i:
                break
            print(i, j)
    Show the answer

    Answer: D

    break ends only the inner loop. When i is 0 it breaks at once; when i is 1 it prints 1 0 and breaks at j == 1; when i is 2 it prints 2 0 and 2 1 before breaking.

    Run this code in the editor
  9. Question 9 · Easy

    What is the output of this code?

    fruits = ["apple", "mango", "kiwi"]
    for i, fruit in enumerate(fruits, start=1):
        print(i, fruit)
    Show the answer

    Answer: B

    enumerate pairs each item with a counter, and start=1 makes the counter begin at 1 instead of 0. Unpacking into i, fruit prints the two values separately, not as a tuple.

    Run this code in the editor
  10. Question 10 · Medium

    What is the output of this code?

    names = ["Ana", "Ben", "Cy"]
    scores = [90, 85]
    for name, score in zip(names, scores):
        print(name, score)
    Show the answer

    Answer: C

    zip stops as soon as the shortest input runs out. scores has only two items, so Cy is never paired and nothing is filled in for it.

    Run this code in the editor
  11. Question 11 · Medium

    What is the output of this code?

    total = 0
    for i in range(1, 5):
        total += i
    print(i, total)
    Show the answer

    Answer: D

    range(1, 5) gives 1, 2, 3 and 4, so total is 10. The loop variable keeps its last value after the loop ends, and that value is 4, not 5.

    Run this code in the editor
  12. Question 12 · Hard

    What is the output of this code?

    nums = [1, 2, 4, 5, 6]
    for n in nums:
        if n % 2 == 0:
            nums.remove(n)
    print(nums)
    Show the answer

    Answer: B

    Removing an item shifts the later items left while the loop's position moves on, so the item after each removed one is skipped. After 2 is removed, 4 slides into its place and is never checked. Loop over a copy (nums[:]) instead.

    Run this code in the editor
  13. Question 13 · Easy

    Which error does this code raise?

    for i in range(0, 1, 0.25):
        print(i)
    Show the answer

    Answer: C, TypeError: 'float' object cannot be interpreted as an integer

    range() accepts only integers for its start, stop and step. A float step such as 0.25 raises TypeError; to count in steps of 0.25, loop over integers and divide, for example i / 4.

    Run this code in the editor
  14. Question 14 · Medium

    Which error does this code raise?

    for i in range(0):
        print("inside")
    print(i)
    Show the answer

    Answer: A, NameError: name 'i' is not defined

    range(0) is empty, so the loop body never runs and i is never assigned. A loop variable exists after the loop only if the loop ran at least once.

    Run this code in the editor
  15. Question 15 · Hard

    Which error does this code raise?

    stock = {"pen": 0, "ink": 4, "nib": 0}
    for item in stock:
        if stock[item] == 0:
            del stock[item]
    Show the answer

    Answer: D, RuntimeError: dictionary changed size during iteration

    Deleting a key while looping over the same dictionary changes its size, and Python stops with RuntimeError. Loop over a copy of the keys instead: for item in list(stock):.

    Run this code in the editor
  16. Question 16 · Easy

    How many times does the body of for i in range(2, 11, 2): run?

    Show the answer

    Answer: B, 5

    The range gives 2, 4, 6, 8 and 10: the stop value 11 is excluded, but 10 is below it, so it is included. That is five values, so the body runs five times.

  17. Question 17 · Medium

    When does the else block of a for loop run?

    Show the answer

    Answer: A, When the loop finishes without hitting break

    A loop's else runs once, after the loop ends normally, including when there was nothing to loop over. It is skipped when break ends the loop, which makes it handy for "not found" cases.

  18. Question 18 · Medium

    Inside for i in range(3):, the loop body sets i = 10. What happens to the loop?

    Show the answer

    Answer: C, It still runs with i = 0, 1 and 2

    Each pass of a for loop takes the next value from the range and assigns it to i, so changing i inside the body has no effect on the next pass. To control the count yourself, use a while loop.

  19. Question 19 · Easy

    Which loop prints 5, 4, 3, 2, 1, one number per line?

    Show the answer

    Answer: A

    Counting down needs a negative step, and the stop value is excluded, so the stop must be 0 to include 1. range(5, 1, -1) stops at 2, and the last two ranges are empty because their step points away from the stop.

  20. Question 20 · Hard

    Which code removes every even number from nums = [2, 4, 6, 7], leaving [7]?

    Show the answer

    Answer: D

    nums[:] is a copy, so removing items from nums does not disturb the loop. Looping over nums itself skips items (it leaves [4, 7]), the range version runs past the shrinking list with IndexError, and pop() removes from the end.

Keep going