Every problem in the chapter beside the book’s answer, a chapter at a time as you scroll.

Chapter 5: Loops

28 problems · 0 figures

Concepts in Practice 5.1.1 §5.1 source ↗

Fibonacci is a series of numbers in which each number is the sum of the two preceding numbers. The Fibonacci sequence starts with two ones: 1, 1, 2, 3, . . . . Consider the following code that prints all Fibonacci numbers less than 20, and answer the following questions.

# Initializing the first two Fibonacci numbers
f = 1
g = 1
print (f, end = ' ')

# Running the loop while the last Fibonacci number is less than 20
while g < 20:
  print(g, end = ' ')
  # Calculating the next Fibonacci number and updating the last two sequence numbers
  temp = f
  f = g
  g = temp + g
How many times does the loop execute?
  1. a.
    5
  2. b.
    6
  3. c.
    7

Answer

B. 6
The loop runs six times for values of g = 1 , 2 , 3 , 5 , 8 , and 13 .

Concepts in Practice 5.1.2 §5.1 source ↗

Fibonacci is a series of numbers in which each number is the sum of the two preceding numbers. The Fibonacci sequence starts with two ones: 1, 1, 2, 3, . . . . Consider the following code that prints all Fibonacci numbers less than 20, and answer the following questions.

# Initializing the first two Fibonacci numbers
f = 1
g = 1
print (f, end = ' ')

# Running the loop while the last Fibonacci number is less than 20
while g < 20:
  print(g, end = ' ')
  # Calculating the next Fibonacci number and updating the last two sequence numbers
  temp = f
  f = g
  g = temp + g
What is the variable g's value when the while loop condition evaluates to False?
  1. a.
    13
  2. b.
    20
  3. c.
    21

Answer

C. 21
21 is the first Fibonacci number larger than 20, and for g = 21, the condition will evaluate to False for the first time.

Concepts in Practice 5.1.3 §5.1 source ↗

Fibonacci is a series of numbers in which each number is the sum of the two preceding numbers. The Fibonacci sequence starts with two ones: 1, 1, 2, 3, . . . . Consider the following code that prints all Fibonacci numbers less than 20, and answer the following questions.

# Initializing the first two Fibonacci numbers
f = 1
g = 1
print (f, end = ' ')

# Running the loop while the last Fibonacci number is less than 20
while g < 20:
  print(g, end = ' ')
  # Calculating the next Fibonacci number and updating the last two sequence numbers
  temp = f
  f = g
  g = temp + g
What are the printed values in the output?
  1. a.
    1 1 2 3 5 8 13
  2. b.
    1 2 3 5 8 13
  3. c.
    1 1 2 3 5 8 13 21

Answer

A. 1 1 2 3 5 8 13
The code first prints the variable f's initial value. Then, at each iteration, g's value is printed, and g's value throughout the code's execution will be 1 , 2 , 3 , 5 , 8 , and 13 . Thus, all printed values are 1 , 1 , 2 , 3 , 5 , 8 , and 13 .

Concepts in Practice 5.1.4 §5.1 source ↗

Given the code, answer the following questions.

n = 4
while n > 0:
  print(n)
  n = n - 1

print("value of n after the loop is", n)
How many times does the loop execute?
  1. a.
    3
  2. b.
    4
  3. c.
    5

Answer

B. 4
The loop runs for n = 4, 3 , 2 , 1 .

Concepts in Practice 5.1.5 §5.1 source ↗

Given the code, answer the following questions.

n = 4
while n > 0:
  print(n)
  n = n - 1

print("value of n after the loop is", n)
Which line is printed as the last line of output?
  1. a.
    value of n after the loop is -1.
  2. b.
    value of n after the loop is 0.
  3. c.
    value of n after the loop is 1.

Answer

B. value of n after the loop is 0.
The loop's termination condition is n = 0; therefore, the value of n after the loop equals 0 . The last printed line will be: value of n after the loop is 0.

Concepts in Practice 5.1.6 §5.1 source ↗

Given the code, answer the following questions.

n = 4
while n > 0:
  print(n)
  n = n - 1

print("value of n after the loop is", n)
What happens if the code is changed as follows?
n = 4
while n > 0:
  print(n)
  # Modified line
  n = n + 1

print("value of n after the loop is", n)
  1. a.
    The code will not run.
  2. b.
    The code will run for one additional iteration.
  3. c.
    The code will never terminate.

Answer

C. The code will never terminate.
Since the initialization value for n equals 4 and the value of n is only increasing, the loop condition will always remain true. The loop will never terminate.

Concepts in Practice 5.2.1 §5.2 source ↗

A string variable can be considered a container of multiple characters, and hence can be iterated on. Given the following code, answer the questions.

str_var = "A string"

count = 0
for c in str_var:
  count += 1

print(count)
What is the program's output?
  1. a.
    7
  2. b.
    8
  3. c.
    9

Answer

B. 8
Eight characters exist in the str_var. Iterating over all characters and incrementing the value of count variable at each iteration results in the count's value of 8 .

Concepts in Practice 5.2.2 §5.2 source ↗

A string variable can be considered a container of multiple characters, and hence can be iterated on. Given the following code, answer the questions.

str_var = "A string"

count = 0
for c in str_var:
  count += 1

print(count)
What's the code's output if the line count += 1 is replaced with count *= 2?
  1. a.
    0
  2. b.
    16
  3. c.
    28

Answer

A. 0
Since the initial count's value is 0 , multiplying count by any number results in the output of 0 .

Concepts in Practice 5.2.3 §5.2 source ↗

A string variable can be considered a container of multiple characters, and hence can be iterated on. Given the following code, answer the questions.

str_var = "A string"

count = 0
for c in str_var:
  count += 1

print(count)
What is printed if the code is changed as follows?
str_var = "A string"

count = 0
for c in str_var:
  count += 1
  # New line
  print(c, end = '*')

print(count)
  1. a.
    A string*
  2. b.
    A*s*t*r*i*n*g*
  3. c.
    A* *s*t*r*i*n*g*

Answer

C. A* *s*t*r*i*n*g*
The added line prints each character that is looped on (character c), and prints an additional * after the character.

Concepts in Practice 5.2.4 §5.2 source ↗

What are the arguments to the range() function for the increasing sequence of every 3rd integer from 10 to 22 (inclusive of both ends)?
  1. a.
    range(10, 23, 3)
  2. b.
    range(10, 22, 3)
  3. c.
    range(22, 10, -3)

Answer

A. range(10, 23, 3)
The output will be an increasing sequence between 10 and 22 (inclusive of both): 10 , 13 , 16 , 19 , and 22 .

Concepts in Practice 5.2.5 §5.2 source ↗

What are the arguments to the range() function for the decreasing sequence of every integer from 5 to 1 (inclusive of both ends)?
  1. a.
    range(5, 1, 1)
  2. b.
    range(5, 1, -1)
  3. c.
    range(5, 0, -1)

Answer

C. range(5, 0, -1)
The expression starts a sequence from 5 , decreases by 1 at every step, and ends at 1 .

Concepts in Practice 5.2.6 §5.2 source ↗

What is the sequence generated from range(-1, -2, -1)?
  1. a.
    1
  2. b.
    -1, -2
  3. c.
    -2

Answer

A. 1
The range() function generates a descending sequence, beginning from -1 until -2. Hence, the output is -1.

Concepts in Practice 5.2.7 §5.2 source ↗

What is the output of the range(1, 2, -1)?
  1. a.
    1
  2. b.
    1, 2
  3. c.
    empty sequence

Answer

C. empty sequence
When the step size is negative, the generated sequence will be in descending order. Hence, start must be larger than end; otherwise, no sequence will be generated.

Concepts in Practice 5.2.8 §5.2 source ↗

What is the output of range(5, 2)?
  1. a.
    0, 2, 4
  2. b.
    2, 3, 4
  3. c.
    empty sequence

Answer

C. empty sequence
When two arguments are provided to the range() function, arguments are considered as start and end of the sequence, and the step size will be 1 . When step size is positive, the generated sequence will be in ascending order, and hence, start must be less than end. Otherwise, no sequence will be generated.

Concepts in Practice 5.3.1 §5.3 source ↗

Given the following code, how many times does the print statement execute?
i = 1
while i <= 5:
  j = 1
  while i + j <= 5:
    print(i, j)
    j += 1
  i += 1
  1. a.
    5
  2. b.
    10
  3. c.
    25

Answer

B. 10
The combination of i and j values, (i, j), that meet the inner and outer loop conditions are as follows:
(1, 1), (1, 2), (1, 3), (1, 4),
(2, 1), (2, 2), (2, 3),
(3, 1), (3, 2),
(4, 1)

Concepts in Practice 5.3.2 §5.3 source ↗

What is the output of the following code?
i = 1

while i <= 2:
  j = 1
  while j <= 3:
    print('*', end = '')
    j += 1
  print()
  i += 1
  1. a.
    ******
  2. b.
    ***
    ***
  3. c.
    **
    **
    **

Answer

B.
***
***
Each inner loop's full execution prints three "*" characters, and the outer loop executes twice.

Concepts in Practice 5.3.3 §5.3 source ↗

Which program prints the following output?
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
  1. a.
    i = 1
    while i <= 4:
      while j <= 4:
        print(i * j, end = ' ')
        j += 1
      print()
      i += 1
  2. b.
    i = 1
    while i <= 4:
      j = 1
      while j <= 4:
        print(i * j, end = ' ')
        j += 1
      print()
      i += 1
  3. c.
    i = 1
    while i <= 4:
      j = 1
      while j <= 4:
        print(i * j, end = ' ')
        j += 1
      i += 1

Answer

B.
i = 1
while i <= 4:
  j = 1
  while j <= 4:
    print(i * j, end = ' ')
    j += 1
  print()
  i += 1
Each line i of the output (i = 1 , 2 , 3 , and 4 ) contains i times values 1 through 4 .
Hence, the outer loop executes while i <= 4, and the inner loop iterates overj while j's value is less than or equal to 4 .

Concepts in Practice 5.3.4 §5.3 source ↗

Given the following code, how many times does the outer loop execute?
for i in range(3):
  for j in range(4):
    print(i, ' ', j)
  1. a.
    3
  2. b.
    4
  3. c.
    12

Answer

A. 3
The outer loop's execution range is 0 , 1 , and 2 ; hence, the outer loop executes three times.

Concepts in Practice 5.3.5 §5.3 source ↗

Given the following code, how many times does the inner loop execute?
for i in range(3):
  for j in range(4):
    print(i, ' ', j)
  1. a.
    4
  2. b.
    12
  3. c.
    20

Answer

B. 12
The inner loop is evaluated four times (j = 0, 1 , 2 , and 3 ) for every i's value set by the outer loop. In the given example i = 0, 1 , and 2 ; hence, the total number of times the inner loop executes is 3 * 4 = 12.

Concepts in Practice 5.3.6 §5.3 source ↗

Which program prints the following output?
0 1 2 3
0 2 4 6
0 3 6 9
  1. a.
    for i in range(4):
      for j in range(4):
        print(i * j, end = ' ')
      print()
  2. b.
    for i in range(1, 4):
      for j in range(4):
        print(i * j)
  3. c.
    for i in range(1, 4):
      for j in range(4):
        print(i * j, end = ' ')
      print()

Answer

C.
for i in range(1, 4):
  for j in range(4):
    print(i * j, end = ' ')
  print()
The printed output displays three rows with each row i displaying i * values in the range of 0 to 3 . Hence, the code must iterate over row ID in the outer loop, and in each row, iterate over elements' ID in the range of 0 to 3 .

Concepts in Practice 5.4.1 §5.4 source ↗

What is the following code's output?
string_val = "Hello World"
for c in string_val:
  if c == " ":
    break
  print(c)
  1. a.
    Hello
  2. b.
    Hello World
  3. c.
    H
    e
    l
    l
    o

Answer

C.
H
e
l
l
o
The code prints all characters before the first occurrence of a space character in separate lines. Hence the output is:
H
e
l
l
o

Concepts in Practice 5.4.2 §5.4 source ↗

Given the following code, how many times does the print statement get executed?
i = 1
while True:
  if i%3 == 0 and i%5 == 0:
    print(i)
    break
  i += 1
  1. a.
    0
  2. b.
    1
  3. c.
    15

Answer

B. 1
As soon as the print statement is executed, the break statement causes the loop's termination. Also, for i = 15, the condition (i%3 == 0 and i%5 == 0) is met, and hence the print statement will be executed exactly once.

Concepts in Practice 5.4.3 §5.4 source ↗

What is the final value of i?
i = 1
count = 0
while True:
  if i%2 == 0 or i%3 == 0:
    count += 1
  if count >= 5:
    print(i)
    break
  i += 1
  1. a.
    5
  2. b.
    8
  3. c.
    30

Answer

B. 8
The loop finds the first five numbers that are divisible by 2 or 3 . These numbers are 2 , 3 , 4 , 6 , and 8 , and thus 8 is the final i's value.

Concepts in Practice 5.4.4 §5.4 source ↗

Given the following code, how many times does the print statement get executed?
i = 10
while i >= 0:
  i -= 1
  if i%3 != 0:
    continue
  print(i)
  1. a.
    3
  2. b.
    4
  3. c.
    11

Answer

B. 4
The print statement is executed for numbers within the range of 0 and 10 (inclusive) that are divisible by 3. The printed output is:
9
6
3
0

Concepts in Practice 5.4.5 §5.4 source ↗

What is the following code's output?
for c in "hi Ali":
  if c == " ":
    continue
  print(c)
  1. a.
    h
    i
    
    A
    l
    i
  2. b.
    h
    i
    A
    l
    i
  3. c.
    hi
    Ali

Answer

B.
h
i
A
l
i
The loop checks whether the character being evaluated is a space character or not. If so, the remainder of the loop will be skipped and the space character will not be printed.

Concepts in Practice 5.5.1 §5.5 source ↗

What is the output?
n = 16
exp = 0
i = n
while i > 1:
  if n%2 == 0:
    i = i/2
    exp += 1
  else:
    break
else:
  print(n,"is 2 to the", exp)
  1. a.
    16 is 2 to the 3
  2. b.
    16 is 2 to the 4
  3. c.
    no output

Answer

B. 16 is 2 to the 4
The variable i is initialized to 16 , and the while loop executes with i = 16, 8 , 4 , and 2 . In each loop's iteration, the variable exp's value is incremented by 1. Hence, at the end of the loop, exp = 4. Since the loop terminates without interruption, the else statement after the loop is executed and prints 16 is 2 to the 4.

Concepts in Practice 5.5.2 §5.5 source ↗

What is the output?
n = 7
exp = 0
i = n
while i > 1:
  if n%2 == 0:
    i = i//2
    exp += 1
  else:
    break
else:
  print(n,"is 2 to the", exp)
  1. a.
    no output
  2. b.
    7 is 2 to the 3
  3. c.
    7 is 2 to the 2

Answer

A. no output
The initial i's value is 7 . Hence, in the first loop's iteration, the else statement within the loop executes, and the break statement terminates the loop. Since the loop's execution is interrupted, the else after the loop will not execute and there will be no output.

Concepts in Practice 5.5.3 §5.5 source ↗

What is the output?
numbers = [1, 2, 2, 6]
for i in numbers:
  if i >= 5:
    print("Not all numbers are less than 5.")
    break
  else:
    print(i)
    continue
else:
  print("all numbers are less than 5.")
  1. a.
    1
    2
    2
    6
    Not all numbers are less than 5.
  2. b.
    1
    2
    2
    Not all numbers are less than 5.
  3. c.
    1
    2
    2
    6
    all numbers are less than 5.

Answer

B.
1
2
2
Not all numbers are less than 5.
The loop iterates over all integer values in the list. If a value is less than 5 , the value will be printed, and if the value is greater than 5 , the code prints "Not all numbers are less than 5." and the code's execution terminates.

Loading chapter 6…

Problems and answers are adapted from Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield and Narges Norouzi, OpenStax, and are used under the CC BY-NC-SA 4.0 licence. Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction. Illustrations: Copyright Rice University, OpenStax, under CC BY-NC-SA 4.0 license. This adaptation is released under the same licence, is non-commercial, and is neither affiliated with nor endorsed by OpenStax or Rice University.