While Loops
While Loops
Sometimes we want code to keep running until something changes.
For example:
- Keep asking for a password until it is correct
- Keep counting until you reach a number
- Keep showing a menu until the user exits
A while loop helps us do this.
What Is a While Loop?
A while loop repeats code while a condition is true.
This means Python checks a question first.
If the answer is true, the code runs.
If the answer is false, the loop stops.
count = 1
while count <= 3:
print(count)
count += 1
How This Example Works
Let’s go step by step:
countstarts at1- Python checks: is
count <= 3? - Yes, so it prints
1 - Then
count += 1changes count to2 - Python checks again
- The loop continues until count becomes
4
Then the condition is false, so the loop stops.
Output
1
2
3
Why We Change the Value
Inside many while loops, something must change.
If nothing changes, the condition may stay true forever.
That creates an infinite loop.
number = 1
while number <= 3:
print(number)
number += 1
Another Example
password = ""
while password != "python123":
password = input("Enter password: ")
print("Access granted")
The program keeps asking until the correct password is entered.
Using While to Repeat Messages
times = 1
while times <= 4:
print("Welcome")
times += 1
Code Along
age = 1
while age <= 3:
print("Age:", age)
age += 1
Mini Challenge
Build a counter.
Steps:
- Create a variable called
numberand set it to1 - Use a
whileloop - Print numbers from
1to5 - Increase the number each time
Real World Use Case
Programs use while loops in games, login systems, timers, and menus that keep running until the user stops them.
Quiz
- What does a
whileloop do? - When does a
whileloop stop? - Why do we change the variable inside the loop?
- What is an infinite loop?
Assignment
Create a program that prints Hello five times using a while loop.
Summary
You learned that a while loop repeats code while a condition is true and stops when the condition becomes false.