Tutorials / Python Basics / Lesson 9

while Loops

What You Will Learn

A while loop keeps running as long as a condition is True. Use it when you do not know in advance how many times to repeat.


Your First while Loop

count = 0

while count < 5:
    print(count)
    count = count + 1

Expected output:

0
1
2
3
4

The loop checks the condition before each iteration. When count reaches 5, the condition count < 5 becomes False and the loop stops.

Always make sure the loop will eventually stop. If the condition never becomes False, the loop runs forever (an infinite loop). Press Ctrl+C to stop a runaway program.


Waiting for Valid Input

A common use of while is to keep asking until the user gives a valid answer:

while True:
    answer = input("Type 'yes' or 'no': ")
    if answer == "yes" or answer == "no":
        break
    print("Invalid input. Try again.")

print(f"You chose: {answer}")

Example interaction:

Type 'yes' or 'no': maybe
Invalid input. Try again.
Type 'yes' or 'no': yes
You chose: yes

while True creates a loop that runs forever — until you use break to exit.


break — Exit the Loop Early

break immediately exits the loop:

for i in range(10):
    if i == 5:
        break
    print(i)

Expected output:

0
1
2
3
4

The loop stops as soon as i equals 5.


continue — Skip to the Next Iteration

continue skips the rest of the current iteration and goes to the next one:

for i in range(8):
    if i % 2 == 0:
        continue
    print(i)

Expected output:

1
3
5
7

Even numbers are skipped because continue jumps to the next iteration before print runs.


A Guessing Game

import random

secret = random.randint(1, 10)
attempts = 0

print("Guess the number (1-10)")

while True:
    guess = int(input("Your guess: "))
    attempts += 1

    if guess < secret:
        print("Too low!")
    elif guess > secret:
        print("Too high!")
    else:
        print(f"Correct! You got it in {attempts} attempt(s).")
        break

Example interaction:

Guess the number (1-10)
Your guess: 5
Too low!
Your guess: 8
Too high!
Your guess: 6
Correct! You got it in 3 attempt(s).

for vs while

Use for whenUse while when
You know how many times to repeatYou do not know how many times
Looping over a list or rangeWaiting for a condition to change
Iterating over a collectionRepeating until the user quits

What You Learned

  • while loops repeat as long as a condition is True
  • while True runs forever until break exits the loop
  • break exits a loop immediately
  • continue skips to the next iteration

In the next lesson, you will learn how to write reusable code with functions.