Iteration (while-loops)

Bisc syntax and examples.

Overview

For loops are suitable for situations where we know how many times we want to repeat a certian piece of code. However, if the number of iterations is unknown, we can use a while loop. This loop allows repeating a block of code as long as a certain condition is met.

Basic Syntax

Example 1.

The following code repeats until the user enters anything other than “1234”.

psw = input("Enter a password: ")
while psw == '1234':
    print("This is not a good password!")
    psw = input("Enter a password: ")

print("Thank you!")

How can we change the code so that it repeats until the user enters a password of length greater than 8?

# Repeats until the user enters a password more than 8 characters long.
psw = input("Enter a password: ")
while len(psw) < 8:
    print("This is a short password!")
    psw = input("Enter a password: ")

print('Thank you!')

Example 2.

The following code counts down from 5 to 1 and then prints Booom!

# Counts down from 5 to 1.
c = 5
while c >= 1:
    print(c)
    c = c - 1
print("Booom!")

This while loop is equivalent to the following for loop.

# Counts down from 5 to 1.
for c in range(5, 0, -1):
    print(c)

print("Booom!")

Every for loop can be written as a while loop. However, it is usually clearer and shorter if you use a for loop for situations where the number of iterations is known before-hand (as in the count-down example)

Exercise 1

Explain in your own words what the following code does, then run it to check if your understanding is correct or not.

c = 0
answer = input("Do you like Python? (enter y or n): ")
while answer != 'y':
    print("Are you " + 'really ' * c + "sure you don't like Python?")
    print("I will ask again:")
    answer = input("Do you like Python? (enter y or n): ")
    c = c + 1

print("Thank you! I knew you loved Python!")

Exercise 2

Catch and fix the bug in the following program. It is supposed to skip 2’s while counting down from n to 1. you can run the program with multiple inputs to find the error.

n = int(input("Enter a number: "))
while n != 0:
    print(n)
    n = n - 2
print("Done!")
Solution This is a classic example of an infinite loop. The program will run for ever if the user enters an odd number or a negative number, because n will never be equal to 0. To fix this issue, change the loop condition to be while n > 0.

Breaking Out of a Loop

The following is another way to write the password example.

while True:
    psw = input("Enter a password: ")
    if len(psw) > 8:
        break
    print("Your password is too short!")

print("Thank you!")

There are two new things going on in the above loop:

  • The while True statement means that we want the loop to repeat for ever.
  • The break statement stops the loop. If password length is greater than 8, the break statement will exit the loop, which means that the following print statement will not be executed.

Exercise 3

Write a program that keeps reading integers from the user until the user enters a negative integer. The program should then print the average of the entered numbers.

Note. To compute the average, we need to know the sum of the entered integers, and how many integers the user entered.

Solution
sum = 0     # for keeping track of the sum
c = 0       # for keeping track of the count
while True:
    num = int(input("Enter a number: "))
    if num < 0:
        break

    sum = sum + num
    c = c + 1

print("Average = ", sum / c)
                

Exercise 4

Rewrite the ‘Are you really really sure’ example above using while True and break.

Solution
c = 0
while True:
    answer = input("Do you like Python? (enter y or n): ")
    if answer == 'y':
        break

    print("Are you " + 'really ' * c + "sure you don't like Python?")
    print("I will ask again:")
    c = c + 1

print("Thank you! I knew you loved Python!")
                

Skipping an Iteration

To skip an iteration, you can use continue. This statement stops the current iteration and goes immediately to the loop condition (skipping the lines below continue).

What does the following program print?

battery = 100
while battery > 0:
    print("Flying drone. Battery = ", battery, "%")
    battery = battery - 10

    if battery > 20:
        continue

    print("WARNING: Low Battery!!")
Solution
Flying drone. Battery =  100 %
Flying drone. Battery =  90 %
Flying drone. Battery =  80 %
Flying drone. Battery =  70 %
Flying drone. Battery =  60 %
Flying drone. Battery =  50 %
Flying drone. Battery =  40 %
Flying drone. Battery =  30 %
WARNING: Low Battery!!
Flying drone. Battery =  20 %
WARNING: Low Battery!!
Flying drone. Battery =  10 %
WARNING: Low Battery!!

© Ibrahim Albluwi. · Last updated: