Chapter Review Questions

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.

  1. When should you prefer a while loop over a for loop?

  2. What is an infinite loop?

    1. Give an example of code that produces one.

    2. How do you stop an infinite loop that is running in a terminal?

  3. What is a sentinel value in a while loop?

    1. Define the term.

    2. Write a short loop that reads integers from the user until the user enters 0, then prints the sum.

  4. Consider this loop:

    n = 10
    while n > 0:
        print(n)
        n -= 3
    
    1. What does it print?

    2. Does it terminate? Explain why.

  5. What does break do inside a while loop?

  6. What does continue do inside a while loop? How is it different from break?

  7. Write a while loop that prints the powers of 2 (1, 2, 4, 8, …) that are less than 1000.

  8. Input validation.

    1. Write a loop that repeatedly asks the user to enter a positive integer and keeps asking until they do.

    2. Why is a while loop more appropriate than a for loop for this task?

  9. Trace the following code by hand and predict the output:

    i = 1
    total = 0
    while i <= 5:
        total += i
        i += 1
    print(total)
    
  10. What is the difference between a pre-condition loop (while condition at the top) and checking the exit condition inside the loop body with break? Give one situation where the break form is cleaner.