Skip to main content

Section 5.12 Evaluate Loops-WE6-P1

Subgoals for Evaluating a Loop.

  1. Determine Loop Components
    1. Start condition and values
    2. Iteration variable and/or update condition
    3. Termination/final condition
    4. Body that is repeated based on indentation
  2. Trace the loop, writing updated values for every iteration or until you identify the pattern

Subsection 5.12.1 Evaluate Loops-WE6-P1

Exercises Exercises

1.
    Q26: What is the output of the following loop?
    i = 1
    while i <= 3:
        j = 1
        s = “”
        while j <= 3:
            s += str(i * j)
        print(s, end=” “)
    
  • 111 222 333
  • 123 246 369
  • 1111 2222 3333
  • 1234 2468 36912
  • 12 24 36
2.
    Q27: What is the output of the following loop?
    for i in range(1, 5):
        for j in range(i):
            print(i, end=” “)
    
  • 1 1 2 1 2 3 1 2 3 4
  • 1 2 1 2 3 1 2 3 4
  • 1 1 2 1 2 3 1 2 3 4 5
  • 0 1 0 1 2 0 1 2 3 0 1 2 3 4
  • 0 1 0 1 2 0 1 2 3 0 1 2 3 4 0 1 2 3 4 5
3.
    Q28: What is the output of the following loop?
    numbers = [1, 2, 3]
    for number in numbers:
        for i in range(1, 4):
            print(number ** i, end = “ “)
    
  • 1 2 3 2 4 6 3 6 9
  • 1 2 3 4 2 4 6 8 3 6 9 12
  • 1 1 1 1 2 4 8 16 3 9 27 81
  • 1 1 1 2 4 8 3 9 27
  • 1 2 4 3 6 9
4.
    Q29: What is the output of the following loop?
    for i in range(4):
        counter = 0
        while counter < 4:
            print(i, end=” “)
            counter += 1
    
  • 1 1 1 2 2 2 3 3 3
  • 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
  • 0 0 0 1 1 1 2 2 2 3 3 3
  • 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3
  • 0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
5.
    Q30: What is the output of the following loop?
    x = [1, 2]
    y = [3, 4]
    for i in x:
        for j in y:
            print(“(“ + i + “, “ + j + “)”, end=” “)
    
  • (1, 3) (2, 4)
  • (1, 3) (2, 3) (1, 4) (2, 4)
  • (1, 3) (1, 4) (2, 3) (2, 4)
  • (1, 2) (1, 3) (1, 4) (2, 3) (2, 4)
  • (1, 4) (1, 3) (2, 4) (2, 3)
You have attempted of activities on this page.