Skip to main content

Section 6.3 Assessment: Writing Loops

Subgoals for Writing a Loop.

  1. Determine purpose of loop
    1. Pick a loop structure (while, for, do_while)
  2. Define and initialize variables
  3. Determine termination condition
    1. Invert termination condition to continuation condition
  4. Write the loop body
    1. Update Loop Control Variable to reach termination

Exercises Exercises

    1.

      Q1: Given the following code segment:
      x = 1
      while ___:
          if x % 2 == 0:
              print(x)
          x = x + 2
      
      Consider the following conditions to replace ___ in the code segment:
      1. x < 0
      2. x <= 1
      3. x < 10
      For which of the conditions will nothing be printed?
    • I only
    • II only
    • I and II only
    • I and III only
    • I, II and III

    2.

      Q2: Given the following code segment which is intended to print the number of integers that evenly divide the integer input_val. (You may assume that input_val > 0.)
      count = 0
      input_val = int(input())
      for k in range(1, input_val):
          if ___:
              count += 1;
      print(count)
      
      Which of the following can be used to replace ___ so that the code will work as intended?
    • input_val % k == 0
    • k % input_val == 0
    • input_val % k != 0
    • input_val / k == 0
    • k / input_val > 0

    3.

      Q3: Which of the following code segments will produce the output:
      1 4 7 10 13 16 19
      k = 1
      while k < 20:
          if k % 3 == 1:
              print(k, end=" ")
          k = k + 3
      
      for k in range(1, 19):
          if k % 3 == 1:
              print(k, end=" ")
      
      k = 1
      while k < 20:
          print(k, end=" ")
          k = k + 3
      
    • I only
    • II only
    • I and II only
    • I and III only
    • I, II and III

    4.

      Q4: What is the maximum number of times “Hello” can be printed?
      k = # a random number such that 1 <= k <= n 
      for p in range(2, k):
          for r in range(1, k - 1):
              print("Hello")
      
    • 2
    • n - 1
    • n - 2
    • (n - 2) * (n - 2)
    • n * n

    5.

    Q5: Fill in the blanks in the following code to create a program that will print the prime numbers between 1 and 100 (inclusive).
    for i in range(__A__, __B__):
        is_prime = False
        for j in range(__C__, __D__):
            if i % j == __E__:
                is_prime = True
        if is_prime:
            print(i, end=" ")
    
    Blank A:
    Blank B:
    Blank C:
    Blank D:
    Blank E:
You have attempted of activities on this page.