AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Hardpythonloops

~105s

The else clause of a for loop

What does this Python program print?

for i in range(3, 8):
    if i % 4 == 0:
        break
else:
    print("none")
print(i)
Show the answer and the worked solution

Correct answer: B.

4

Worked solution

  1. i takes the value 3 first, and 3 % 4 is 3, so the loop continues.
  2. i then takes the value 4, and 4 % 4 is 0, so break fires.
  3. Because the loop was broken out of, the else clause is skipped and none is never printed.
  4. The loop variable survives the loop and still holds 4, so the program prints 4.

Answer: 4.

The idea

A loop else means 'no break happened', which reads better as a nobreak clause. The loop variable is not scoped to the loop in Python, so it remains available afterwards.

Shortcut. The first multiple of 4 in 3 to 7 is 4, so the loop breaks there; a break skips the else, and i keeps the value 4.

Common trap. 7 assumes the loop variable ends on the last value of range(3, 8), as after a full run; the break at i = 4 stops it there.

The else clause of a for loop — Aptitude Question

The else clause of a for loop: What does this Python program print? Answer and worked solution on CodeKairo.

Question

What does this Python program print?

for i in range(3, 8):
    if i % 4 == 0:
        break
else:
    print("none")
print(i)

Options

  1. 3
  2. 4
  3. 7
  4. none followed by 7
Show the answer and the worked solution

Correct answer: B. 4

Worked solution

  1. i takes the value 3 first, and 3 % 4 is 3, so the loop continues.
  2. i then takes the value 4, and 4 % 4 is 0, so break fires.
  3. Because the loop was broken out of, the else clause is skipped and none is never printed.
  4. The loop variable survives the loop and still holds 4, so the program prints 4.

Answer: 4.

The idea

A loop else means 'no break happened', which reads better as a nobreak clause. The loop variable is not scoped to the loop in Python, so it remains available afterwards.

Shortcut. The first multiple of 4 in 3 to 7 is 4, so the loop breaks there; a break skips the else, and i keeps the value 4.

Common trap. 7 assumes the loop variable ends on the last value of range(3, 8), as after a full run; the break at i = 4 stops it there.

All Programming Fundamentals questions · placement mock tests