PCEP Control Flow, Loops, Lists and Logic Practice Question
A developer writes the following code snippet:
for i in range(3):
for j in range(2):
if i == j:break else:
print(i, 'outer')
What is the output?
⚠ Common exam trap
Python Institute often tests the `for-else` behavior in nested loops, and the trap here is that candidates mistakenly think the `else` runs after every outer iteration or that `break` only exits the outer loop, when in fact `break` only exits the innermost loop and the `else` is tied to that inner loop's completion status.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
2 outer
The code uses nested loops with a `for-else` construct. The `else` block executes only if the inner loop completes without a `break`. When `i == j`, the `break` exits the inner loop, skipping the `else`. For `i=0`, `j=0` triggers `break`; for `i=1`, `j=1` triggers `break`; for `i=2`, the inner loop runs `j=0,1` without any `i==j` (since 2 != 0 and 2 != 1), so the `else` executes, printing `2 outer`. Thus, only option B is correct.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
0 outer\n2 outer
Why it's wrong here
For i=0 the inner loop breaks at j=0, so the else is skipped; i=1 also breaks at j=0. Only i=2 exhausts j=0 and j=1 without a match, so the else prints '2 outer' alone. The break suppresses the else for the first two iterations.
- ✓
2 outer
Why this is correct
The inner loop breaks only when i equals j, so for i=0 and i=1 the else clause is skipped. For i=2, j never equals 2, so the inner loop completes and the else runs, printing '2 outer'.
- ✗
0 outer\n1 outer\n2 outer
Why it's wrong here
The inner loop breaks on the first iteration for every i (i equals j at j=0), so the else clause never runs and nothing prints. The claim of three lines assumes the break exits only the inner loop while the outer else still fires, but a break skips the else attached to the loop it terminates.
- ✗
No output
Why it's wrong here
There is output for i=2.
Go deeper
Related to this question
About these practice questions
One of 482 original PCEP practice questions on Courseiva, each with a full explanation and wrong-answer analysis — not exam dumps or protected exam content. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This PCEP practice question is part of Courseiva's free Python Institute certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the PCEP exam.