Chapter Review Questions

Chapter Review Questions#

Note

Source: Adapted from the C# edition (for/reviewfor.rst). C#-specific format-string questions are replaced by f-string equivalents. Python-specific questions on range(), enumerate(), and list comprehensions are added.

  1. Choosing the right loop.

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

    2. What do you gain by using for?

  2. When might you prefer a while loop over a for loop?

  3. When you have nested for loops and reach the bottom of the inner loop body, where does execution go next?

  4. Write a range() expression that produces: 0, 1, 2, 3, 4.

  5. Write a range() expression that produces: 3, 4, 5, 6, 7.

  6. Write a range() expression that produces: 0, 3, 6, 9, 12.

  7. Write a range() expression that produces: 10, 8, 6, 4, 2.

  8. Rewrite the following without using +=:

    total += score
    
  9. Rewrite the following using a compound assignment operator so that big_name appears only once:

    big_name = big_name * 2
    
  10. What does enumerate() give you that a plain for item in seq: loop does not?

  11. What is printed? Trace through by hand before running:

    for i in range(1, 4):
        for j in range(i):
            print(j, end=" ")
        print()
    
  12. What is printed?:

    s = "abcde"
    for i in range(0, len(s), 2):
        print(s[i])
    
  13. Write a list comprehension that produces the cubes of 1 through 5: [1, 8, 27, 64, 125].

  14. Write a list comprehension equivalent to:

    result = []
    for w in ["hello", "world", "python"]:
        if len(w) > 4:
            result.append(w.upper())
    
  15. Two similar expressions.

    1. What is the type and value of [n * 2 for n in range(5)]?

    2. What is the type and value of (n * 2 for n in range(5))?

    3. When would you prefer the second form?