Lesson 7: While Loops

Module 3: Control Flow & Loops · about 12 min · free

A while loop is used when something in the code is supposed to repeat.

In Python, when we want to do something 100 times, obviously we will not write the same code over and over again, but we will put it into a loop.

How the while loop works:

The while loop is used when we don’t know exactly how many times the loop will run, but its progress depends on whether a specific condition is fulfilled.

  • The Condition Check: Before every single run (iteration) of the loop, Python checks if the condition is true (True).
  • Execution: If the condition is true, the code inside the while block runs.
  • Repeat or Exit: After running the code block, the program jumps back to the top and checks the condition again. As soon as the condition becomes false (False), the loop stops and the program moves on to the code below it.
  • ⚠️ Warning: Make sure that something inside your loop changes the condition so it eventually becomes false! Otherwise, you will create an infinite loop that runs forever and freezes your program.

We use this, for example, when we want to validate user input:

number = float(input("Enter a number: ")) # we use datatype float because integer supports only full numbers
divisor = float(input("Enter a divisor: "))
while divisor == 0:
  print("You can't divide by zero!")
  divisor = float(input("Enter divisor again: "))
print(f"{number} / {divisor} = ", number/divisor)

Output

Enter a number: 10
Enter a divisor: 0
You can't divide by zero!
Enter divisor again: 5
10.0 / 5.0 =  2.0

Or when we want to see when a number exceeds some limit:

a = 5
while a <= 10:
  print(f"number a is not bigger than 10 yet")
  a+=1
print("Number a exceeded the limit 10!")

Output

number a is not bigger than 10 yet
number a is not bigger than 10 yet
number a is not bigger than 10 yet
number a is not bigger than 10 yet
number a is not bigger than 10 yet
number a is not bigger than 10 yet
Number a exceeded the limit 10!

There are many more uses for this loop, but you will discover them as you code more actively.

Want XP, levels and progress tracking? Play this lesson in the CodeStart game.

Play Lesson 7