Chapter Review Questions#
Note
Source: Adapted from the C# edition (while/reviewwhile.rst).
Python-specific questions on input() validation and break/continue
are original additions.
When should you prefer a
whileloop over aforloop?What is an infinite loop?
Give an example of code that produces one.
How do you stop an infinite loop that is running in a terminal?
What is a sentinel value in a
whileloop?Define the term.
Write a short loop that reads integers from the user until the user enters
0, then prints the sum.
Consider this loop:
n = 10 while n > 0: print(n) n -= 3
What does it print?
Does it terminate? Explain why.
What does
breakdo inside awhileloop?What does
continuedo inside awhileloop? How is it different frombreak?Write a
whileloop that prints the powers of 2 (1, 2, 4, 8, …) that are less than 1000.Input validation.
Write a loop that repeatedly asks the user to enter a positive integer and keeps asking until they do.
Why is a
whileloop more appropriate than aforloop for this task?
Trace the following code by hand and predict the output:
i = 1 total = 0 while i <= 5: total += i i += 1 print(total)
What is the difference between a pre-condition loop (
whilecondition at the top) and checking the exit condition inside the loop body withbreak? Give one situation where thebreakform is cleaner.