Table of Contents
Which Python Loop Structure Guarantees Execution and Exits on a Specific Condition?
Discover the best loop structure in Python for ensuring user input is read at least once. Learn how the while True loop combined with a break statement provides a robust pattern for handling user input until a specific exit condition, like entering ‘q’, is met.
Question
Which loop structure best ensures user input is read at least once and exits on ‘q’?
A. While read != ‘q’: input(…) with read unused/undefined
B. For i in range(0): input(…)
C. While True: read = input(…); if read == ‘q’: break
D. While condition: … where condition is initially False
Answer
C. While True: read = input(…); if read == ‘q’: break
Explanation
This pattern guarantees one read per iteration and exits cleanly on ‘q’.
The While True: … if … break pattern is the most robust and standard way to create a loop that is guaranteed to execute at least once and then exit based on a condition evaluated inside the loop.
This structure works as follows:
- while True: initiates an infinite loop. The loop’s condition is always True, so it will run forever unless explicitly stopped. This guarantees the code inside the loop will execute at least one time.
- read = input(…) is placed inside the loop, prompting the user for input during each iteration.
- if read == ‘q’: checks if the user’s input matches the exit condition.
- break is a control statement that immediately terminates the innermost loop it is in. When the user enters ‘q’, the if condition becomes true, and break is executed, cleanly exiting the loop.
This pattern avoids the common issues found in other approaches and is widely used for handling sentinel values (like ‘q’) or for input validation.
The other options are incorrect for these reasons:
A is flawed because read would be undefined when the while condition is first checked, raising a NameError. This pattern requires a “priming read” before the loop begins, which can lead to code duplication.
B will never run. range(0) creates an empty sequence, so the for loop has no iterations to perform and its body is never executed.
D will also never run. If the while loop’s condition is False from the start, the program will skip the loop body entirely, failing the requirement to read input at least once.
Python Basics: Learn, Apply & Build Programs certification exam assessment practice question and answer (Q&A) dump including multiple choice questions (MCQ) and objective type questions, with detail explanation and reference available free, helpful to pass the Python Basics: Learn, Apply & Build Programs exam and earn Python Basics: Learn, Apply & Build Programs certificate.