ProgrammingHardIBM · Deloitte · Product Company SDE
What does the following Python 3 code print? def f(): for i in range(5): if i == 3: break else: print("else-no-break") print(i) f()
- A. else-no-break 3
- B. 3
- C. 4
- D. 2
Correct answer: B. 3
The loop's else clause only runs if the loop completes without break; since break fires at i==3, it is skipped, and i keeps its value 3.
More Python Programming questions
- What does the following Python 3 code print? def f(): for i in range(3): pass else: print("else-ran") f()
- What does the following Python 3 code print? while False: print("never") else: print("while-else")
- What does the following Python 3 code print? x = 1 while x < 5: x += 1 if x == 3: break else: print("no-break") print(x)
- What does the following Python 3 code print? print([i for i in range(5) if i != 2][::-1])
- What does the following Python 3 code print? matrix = [[1, 2], [3, 4], [5, 6]] transposed = [[row[i] for row in matrix] for i in range(2)]…
- What does the following Python 3 code print? print(list(enumerate(["a", "b", "c"], start=1)))