SCRIPTING-AND-PROGRAMMING-FOUNDATIONS practice question 9 of 25

A program allows the user to play a game. At the end of each game, the program asks the user if they want to play again. Which programming structure on its own is appropriate to accomplish this task?

Full set: 137 questions
Answer options
A: Nested for loops
B: One for loop
C: One while loop Correct answer
D: If-else statement
Correct Answer:
C. One while loop
Explanation

The scenario describes repeating an action (playing a game) an unknown number of times, based on user input. This is a classic example of indefinite iteration. A while loop is the appropriate structure because it can be set to continue executing the game logic as long as a condition, such as playagain == 'yes', is true. The loop terminates only when the user decides not to play again, changing the condition to false.

Why Incorrect

A. Nested for loops are for iterating through multi-dimensional data or when one definite loop must run inside another; this is not applicable here.
B. A single for loop is used for definite iteration, where the number of repetitions is known beforehand, which is not the case in this scenario.
D. An if-else statement makes a one-time decision. It cannot, by itself, cause the program to loop and play the game again.

References

1. Guttag, J. V. (2016). Introduction to Computation and Programming Using Python (2nd ed.). MIT Press. Chapter 3, "Some Simple Numerical Programs," discusses iteration and the use of loops for repetitive tasks based on conditions.

2. The Python Software Foundation. (2023). The Python Tutorial, 4.3. The while statement. Python 3.12.0 documentation. Retrieved from https://docs.python.org/3/tutorial/controlflow.html#the-while-statement. (The documentation explains that while loops are used for repeated execution as long as an expression is true).

3. Horstmann, C. S. (2019). Core Java SE 9 for the Impatient (2nd ed.). Addison-Wesley Professional. Chapter 1, "Fundamental Programming Structures," Section 1.6.3, "While Loops," describes their use for repeating statements while a condition is true.

Scroll to Top