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 questionsThe 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.
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.
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.
Keep practicing
Take the free GPYC practice test
Ten exam-style questions with answers and explanations, plus the exam facts and study guides.
More questions
Other GPYC practice questions
- Question 1What will the contents of the "__name__" variable be if the program "gpyc.py" is run as a…
- Question 3With a requests session object named "browser", how can the expiration attribute of a coo…
- Question 4What does the attacker do in a SQL Injection attack?
- Question 8An operator able to perform bitwise shifts is coded as (select two answers)
- Question 9Third-party Python modules like Scapy and Beautiful Soup are used for what purpose?
- Question 13After calling a subprocess in a Python program, the program returns an error code of "0".…
