GPYC practice question 6 of 15

What will be the value of the i variable when the while loop finishes its execution0 i = 0 while i != 0: 1 = 1-1 else: i = i + 1

Full set: 75 questions
Answer options
A: 1 Correct answer
B: 0
C: 2
D: the variable becomes unavailable
Correct Answer:
A. 1
Explanation

The variable i is initialized to 0. The while loop's condition, i != 0, is evaluated. Since 0 != 0 is false, the condition is not met, and the body of the while loop is never executed. According to Python's control flow, when a while loop terminates because its condition is false (and not via a break statement), the associated else block is executed. Therefore, the code i = i + 1 in the else block runs, incrementing i from 0 to 1. The final value of i is 1.

Why Incorrect

B. 0: This would be the value if the else block did not execute, but it does because the loop condition was initially false.
C. 2: There is no logical path in this code that would result in i having a value of 2.
D. the variable becomes unavailable: The variable i remains in scope with its updated value after the while...else structure completes.

References

1. Python Software Foundation. "More Control Flow Tools". Python 3.12.3 documentation. Section 4.4, "break and continue Statements, and else Clauses on Loops". This section states, "The else clause is executed... when the condition becomes false (with while)." This confirms the else block executes when the initial condition is false.

2. Lutz, Mark. Learning Python, 5th Edition. O'Reilly Media, 2013. Chapter 13, "The Loop else Block", pp. 397-399. This section explains that the else part of a while loop runs if the loop exits normally (by the test condition failing) but not when the loop is exited by a break statement.

3. Downey, Allen B. Think Python: How to Think Like a Computer Scientist, 2nd Edition. O'Reilly Media, 2015. (Also available via Green Tea Press). While not explicitly covering while...else, Chapter 7, "Iteration," establishes the fundamental principle that a while loop's body is only entered if the condition is true. This supports the reasoning that the loop body is skipped in this scenario.

Scroll to Top