Flow controls: Loops · 1 / 26 Theory

The while loop

A loop repeats a block of code. while repeats it as long as a condition is true.

Structure

counter = 1

while counter <= 3:
    print(counter)
    counter = counter + 1

print("End")
# 1
# 2
# 3
# End

Python checks the condition before each turn. If it is True, it runs the (indented) block and checks again; when it is False, it continues after the loop.

The three pieces of a while

  • Initialization: the variable that controls the loop (counter = 1).
  • Condition: when to continue (counter <= 3).
  • Update: something inside the block that brings the condition closer to False (counter = counter + 1, or its short form counter += 1).

If the condition is never true

The block may run zero times:

n = 10
while n < 5:
    print("never shown")

Countdown

n = 5
while n > 0:
    print(n)
    n -= 1
print("Liftoff!")

When to use while

When you do not know in advance how many turns there will be: reading data until the user types something specific, repeating until a guess is right, dividing a number until it reaches zero…

n = int(input())
total = 0
while n != 0:      # ends when the user types 0
    total += n
    n = int(input())
print(total)

Practice with Using the while statement, Range of numbers and Digits in a number.