These questions follow Repetition. A loop is a bargain: describe one pass precisely and the computer does all of them. The two things worth getting exactly right are how many passes happen, and which lines are inside.

Reading

  1. How many lines does this print, and what is the last one?
    for day in range(1, 8):
        print(f"Day {day}")
  2. Trace it. Give the value of total after each pass, then say what prints.
    weights = [6, 11, 7]
    total = 0
    for weight in weights:
        total = total + weight
    print(total)
  3. Find the fault. This prints 7 when it should print 24.
    weights = [6, 11, 7]
    for weight in weights:
        total = 0
        total = total + weight
    print(total)
  4. How many lines does this print in total?
    for week in range(2):
        for day in range(3):
            print(f"Week {week}, day {day}")

Writing

  1. Write a while loop that keeps asking How many bins? until the answer is made only of digits, then prints Recording 6 bins. Use .isdigit().
  2. Add up every even number from 2 to 20 and print the total. Do it twice — once with a range that steps by 2, and once with a range over every number and an if inside.
  3. Why does range(1, 8) give you a week, and range(1, 7) give you only six days? State the rule in your own words.
  4. Challenge. Keep asking for weights until the user types done, then report the heaviest — without storing anything in a list.

Answers