Skip to content

While Loops

Loops are a way of executing something over and over. The syntax for the while loop is very similar to the if statement:

while <TestExpression>:
  <Block>

In contrast to an if statement where the block executes either 0 or 1 times depending on whether the test expression is True or False, a while loop executes any number of times, continuing as long as the test expression is True. In a if statement if the test expression is True, the block executes once and then continues to the following statment. If the test expression is False, execution jumps over the block and continues with the following statement. If the test expression for a while loop is True, the block is executed. Then, execution continues by going back to the test expression again. If it still evaluates to True, the block is executed again, and execution continues by going back to the test expression one more time. This continues as long as the test expression evaluates to True, and again as many times as you need. Once the test expression is False, execution jumps to the next statement. There is no guarantee that the test expression eventually becomes False, however. The loop could keep running forever, which is known as an infinite loop. Here is an example while loop:

i = 0
while i < 10:
  print(i)
  i = i + 1

This code will execute the inner block as long as the test expression, while i < 10, is True. Inside the block, it prints i and then adds 1 to i. In this example, the while loop repeats 10 times, printing the numbers from 0 to 9. At the end of the loop, the value of i is 10.

Quiz 2.16

What does this program do?

i = 0
while i != 10:
  i = i + 2
  print(i)
  • A) Produce an error
  • B) Print out 2, 4, 6, 8, 10.
  • C) Print out 0, 2, 4, 6, 8.
  • D) Print out 0 , 2, 4, 6, 8, 10.
  • E) Run forever
Answer
  • B) Print out 2, 4, 6, 8, 10.

Quiz 2.17

What does the following code do?

i = 1
while i != 10:
  i = i + 2
  print(i)
  • A) Produce an error.
  • B) Print out 2, 4, 6, 8.
  • C) Print out 1, 3, 5, 7, 9.
  • D) Print out 3, 5, 7, 9.
  • E) Run forever.
Answer
  • E) Run forever.

Quiz 2.18

Define a procedure, print_numbers, that takes as input a positive whole number, and prints out all the whole numbers from 1 up to and including the input number.

print_numbers(3)
# 1
# 2
# 3
Answer
def print_numbers(n):
  i = 1
  while i < = n:
    print(i)
    i = i + 1

Another approach:

def print_numbers(n):
  i = 0
  while i < n:
    i = i + 1
    print(i)

Baby Blocks (Factorial)

Suppose we have four blocks and a baby. We want to know how long the baby can play with the blocks without getting bored. The baby wants to try all of the different ways of arranging the blocks by stacking them in a tower.
Think about the baby’s choices for the first block, she has four. Let’s say she reaches for the red block first. When she reaches for the second block she is down to just three choices. If she stacks the green block on top of the red block, she has two choices left, the blue block and the purple block. Next, the baby picks the purple one. Therefore, for her fourth block, the baby only has one choice, the blue one.
To figure out the total number of choice we want to multiply the number of choices for the first block by the number of choices for the second block, by the number of choices for the third block, all the way to the fourth block. The function that you are computing is factorial. For any input n, you compute the factorial, which is the number of ways of arranging n items.

factorial(n) = n · (n-1) · (n-2) · ... · 2 · 1

Quiz 2.19

Define a procedure, factorial, that takes one number as its input and outputs the factorial of that number.

Answer
def factorial (n):
  result = 1
  while n >=1 :
    result = result * n
    n = n -1
  return result

print(factorial(4)) # 24

This result states that there are 24 different ways for the baby to arrange the blocks. You could also use this program to figure out how many different ways to arrange a deck of 52 playing cards, which is a really big number. Give it a try!

break Statement

Break gives us a way to break out of a loop, even if the test condition is true. The typical structure of the loop with a break looks like this:

while <TestExpression>:
  <Code>
  if <BreakTest>:
    break # stop executing the while loop
  <More Code>
<After While>

The break statement jumps out of the loop to <After While>. Here is an example showing how we could rewrite print_numbers using break:

def print_numbers(n):
  i = 1
  while True:
    if i > n:
      break
    print(i)
    i = i + 1

This has the same behavior as the previous implementation, except now the test condition for the while loop is True. This is a bad example: if there is a way to write a loop without using break, it is usually best to avoid it. We will see soon an example where it is more difficult to write the loop without using break, since it is not clear before executing part of the block if the loop should continue repeating.

Quiz 2.20

Which of the following are always equivalent to:

while <T>:
  <S>
  • A)

    while <T>:
      if False:
        break
      <S>
    
  • B)

    while <T>:
      <S>
      break
    

  • C)

    while True:
      if <T>:
        break
      <S>
    

  • D)

    while <T>:
      <S>
      if <T>:
        <S>
      else:
        break
    

Answer

A) and D)

Back to top