Lecture 8 - Exercises

8A - For Loops

  1. What does the following program print?

    m = 0
    for n in [1.8, 4.2, 1.6, 2.0, 1.88]:
      m += int(n)
    print(m)
  2. What is the output of the following program?

    s = ""
    i = 1
    for digit in ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]:
      if len(digit) < 5 and i % 2 == 1:
         s = digit + s
      i += 1
    print(s)

8B - The range function

What does each of the following range calls, converted to a list, evaluate to?

  1. list(range(3))
  2. list(range(4, 7))
  3. list(range(4, 0, -1))

How many elements are in the following ranges?

  1. range(732)

  2. range(6, 88)

  3. range(4, 2)

  4. range(20, 21)

  5. range(0)

  6. What does the following program print?

for x in range(1,4):
   print(x + x * x, end=str(x))

Consider the following incomplete program:

x = 
y = 
for z in range(x, y):
  print("WWU")
  1. What pairs of values could be assigned to the variables x and y so that the program prints WWU 43 times? Select all correct choices.

    1. x: 0 y: 44
    2. x: -21 y: 22
    3. x: -21 y:21
    4. x: -789 y: -746
    5. x: -789 y: 746
    6. x: 1 y: 44
  2. Write a program that prompts the user for a positive integer \(p\) and uses a for loop to print the powers of 2 up to \(2^p\) (starting at \(p\) == 0).