Python while Loops
Learn how to repeatedly execute Python code while a condition
remains true. In this lesson, you will learn how
while loops work, how to control them safely,
validate user input, avoid infinite loops, and build
practical programs.
What You Will Learn
- Understand how
whileloops work. - Write loops controlled by conditions.
- Build counter-controlled loops.
- Use
breakandcontinue. - Validate user input using loops.
- Understand and prevent infinite loops.
- Use
while...else. - Build practical programs using
while.
What Is a while Loop?
A while loop repeatedly executes a block
of code as long as a specified condition is
True.
Unlike a for loop, which is commonly used when
iterating over a known sequence, a while loop
is useful when repetition depends on a condition.
count = 1
while count <= 5:
print(count)
count += 1
1 2 3 4 5
The loop continues while count <= 5 remains
true. Once count becomes 6, the condition
becomes false and the loop stops.
A while loop asks:
"Is the condition still true?"
If yes, execute the loop body again.
Why Use while?
A while loop is especially useful when you
do not know exactly how many times a task needs to repeat.
Common situations include:
- Waiting for valid user input.
- Repeating a menu until the user chooses Exit.
- Running a process while a condition is true.
- Retrying an operation.
- Creating game loops.
- Counting until a target is reached.
- Monitoring a changing condition.
for vs while
Use for when you are naturally
iterating through a sequence or a known range.
Use while when repetition should
continue until a condition changes.
Basic Syntax
The basic structure of a Python while loop is:
while condition:
# code to execute
The condition must produce a Boolean result:
True or False.
number = 1
while number <= 3:
print("Hello")
number += 1
Hello Hello Hello
The variable is updated during every iteration so that the condition eventually becomes false.
The Loop Condition
The condition controls whether the loop continues.
temperature = 30
while temperature > 25:
print("Temperature is high")
temperature -= 1
Temperature is high Temperature is high Temperature is high Temperature is high Temperature is high
The loop runs while the temperature is greater than 25. Once it reaches 25, the condition becomes false.
Think Step by Step
- Check the condition.
- If it is true, run the body.
- Update the relevant value.
- Check the condition again.
- Stop when the condition becomes false.
Counter-Controlled Loops
One of the simplest uses of a while loop is
counting.
count = 1
while count <= 5:
print(count)
count += 1
Here, count is called a
loop control variable.
A counter-controlled loop normally contains:
- An initial value.
- A condition.
- An update operation.
Updating the Variable
One of the most important rules of a while
loop is to make sure the condition can eventually
become false.
number = 0
while number < 5:
print(number)
number += 1
The expression number += 1 increases the
variable by one after every iteration.
Increment by Another Amount
number = 2
while number <= 10:
print(number)
number += 2
2 4 6 8 10
Counting Backwards
A while loop can also count downward.
count = 5
while count >= 1:
print(count)
count -= 1
print("Go!")
5 4 3 2 1 Go!
The operator -= decreases the value of
count by one during each iteration.
while with User Input
One of the most practical uses of a while
loop is repeatedly asking the user for input until a
particular condition is satisfied.
answer = ""
while answer != "yes":
answer = input("Enter yes to continue: ")
print("Thank you!")
The program keeps asking the user until they enter
yes.
Menu Example
choice = ""
while choice != "3":
print("1. View Profile")
print("2. Settings")
print("3. Exit")
choice = input("Choose an option: ")
print("Program closed.")
Real-World Use
Console applications frequently use this pattern to keep a menu active until the user selects an exit option.
Input Validation with while
A loop can force a program to continue asking for input until the user provides valid information.
age = int(input("Enter your age: "))
while age < 0:
print("Age cannot be negative.")
age = int(input("Enter your age again: "))
print("Age accepted:", age)
Range Validation
marks = int(input("Enter marks: "))
while marks < 0 or marks > 100:
print("Marks must be between 0 and 100.")
marks = int(input("Enter marks again: "))
print("Valid marks:", marks)
Input validation prevents invalid data from entering the rest of your program.
Using break
The break statement immediately terminates
the loop.
number = 1
while number <= 10:
if number == 5:
break
print(number)
number += 1
1 2 3 4
When number becomes 5, break
stops the loop immediately.
When Is break Useful?
Use break when you have found what
you were looking for, received an exit command,
or need to stop the loop immediately.
Using continue
The continue statement skips the rest of the
current iteration and moves to the next iteration.
number = 0
while number < 6:
number += 1
if number == 3:
continue
print(number)
1 2 4 5 6
When the number becomes 3, continue skips
the print() statement for that iteration.
When using continue in a
while loop, make sure the loop
control variable is updated before the
continue statement when necessary.
Otherwise, you may accidentally create an
infinite loop.
while with else
Python allows an else block to be attached
to a while loop.
The else block runs when the loop finishes
normally because its condition becomes false.
count = 1
while count <= 3:
print(count)
count += 1
else:
print("Loop finished.")
1 2 3 Loop finished.
When break Is Used
count = 1
while count <= 5:
if count == 3:
break
print(count)
count += 1
else:
print("Loop finished.")
1 2
Because break terminated the loop,
the else block did not run.
Nested while Loops
A nested loop is a loop placed inside another loop.
row = 1
while row <= 3:
column = 1
while column <= 3:
print(row, column)
column += 1
row += 1
1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3
For every iteration of the outer loop, the inner loop runs completely.
Nested loops can become difficult to understand if the control variables are not managed clearly. Give each loop its own appropriate variable.
Infinite Loops
An infinite loop is a loop that never reaches a condition that makes it stop.
number = 1
while number <= 5:
print(number)
This loop never changes number. Therefore,
number <= 5 remains true forever.
Correct Version
number = 1
while number <= 5:
print(number)
number += 1
Always identify what will eventually make the
while condition false.
Intentional Infinite Loops
Infinite loops are sometimes intentional. For example, a continuously running application may use:
while True:
command = input("Enter command: ")
if command == "exit":
break
In this pattern, break provides the exit
condition.
Practical Real-World Examples
Example 1 — Countdown Timer Logic
seconds = 5
while seconds > 0:
print("Seconds remaining:", seconds)
seconds -= 1
print("Time's up!")
Seconds remaining: 5 Seconds remaining: 4 Seconds remaining: 3 Seconds remaining: 2 Seconds remaining: 1 Time's up!
Example 2 — Password Attempts
correct_password = "python123"
attempts = 3
while attempts > 0:
password = input("Enter password: ")
if password == correct_password:
print("Login successful.")
break
attempts -= 1
print("Incorrect password.")
else:
print("Account temporarily locked.")
This example combines a loop, condition, counter and
break to create a simple authentication flow.
Example 3 — Shopping Cart Menu
total = 0
choice = ""
while choice != "3":
print("\n1. Add Rs. 500")
print("2. Add Rs. 1000")
print("3. Checkout")
choice = input("Choose: ")
if choice == "1":
total += 500
elif choice == "2":
total += 1000
print("Total:", total)
Example 4 — Find a Number
numbers = [10, 25, 40, 55, 70]
index = 0
found = False
while index < len(numbers):
if numbers[index] == 40:
found = True
break
index += 1
print("Found:", found)
Found: True
Common Mistakes
1. Forgetting the Colon
while count < 5
print(count)
Python requires a colon after the loop condition.
2. Forgetting to Update the Control Variable
count = 1
while count <= 5:
print(count)
The value of count never changes, so the
loop never ends.
3. Updating in the Wrong Direction
count = 5
while count > 0:
print(count)
count += 1
Here the value increases instead of decreasing, so the condition will remain true.
4. Incorrect Indentation
count = 1
while count <= 5:
print(count)
count += 1
The statements belonging to the loop must be indented.
5. Accidentally Creating an Infinite Loop with continue
If continue executes before the
control variable is updated, the loop may return
to the same condition forever.
Practice Exercises
Exercise 1 — Count to 10
Use a while loop to print the numbers
from 1 to 10.
Exercise 2 — Countdown
Print the numbers from 10 down to 1 and then display
Go!.
Exercise 3 — Even Numbers
Use a while loop to print all even
numbers from 2 to 20.
Exercise 4 — Sum Numbers
Calculate the sum of numbers from 1 to 100 using
a while loop.
Exercise 5 — Valid Age
Keep asking the user for an age until a valid non-negative value is entered.
Exercise 6 — Password System
Give the user three attempts to enter the correct password.
Exercise 7 — Menu Program
Create a menu that continues running until the user selects an Exit option.
Exercise 8 — Guessing Game
Create a number guessing game that continues until the user guesses the correct number.
Mini Challenge — Number Guessing Game
Build a simple number guessing game using a
while loop.
Your program should:
- Choose a secret number.
- Ask the user to guess it.
- Tell the user whether the guess is too high or too low.
- Continue asking until the correct number is entered.
- Count the number of attempts.
- Display a success message at the end.
secret_number = 42
guess = 0
attempts = 0
while guess != secret_number:
guess = int(input("Guess the number: "))
attempts += 1
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print("Correct!")
print("Attempts:", attempts)
Upgrade the Challenge
Add a maximum number of attempts. For example, allow the player only 7 guesses before the game ends.
Try building the program yourself before looking for alternative solutions. Focus on understanding why the loop condition changes after every guess.
Quick Knowledge Check
1. When does a while loop continue running?
2. What is essential for a counter-controlled while loop?
3. What does break do?
4. What does continue do?
5. What is an infinite loop?
6. What happens to while...else when break runs?
7. Which statement decreases a variable by one?
8. Which loop is especially useful when repetition depends on a condition?
Lesson Summary
A Python while loop repeatedly executes
code as long as its condition remains true.
- A
whileloop is controlled by a condition. - The condition is checked before each iteration.
- The loop should normally contain a way for the condition to change.
- Counter variables are commonly used with
while. breakimmediately terminates a loop.continueskips the current iteration.while...elsecan detect normal completion.- Nested
whileloops can solve more complex problems. - Input validation is a practical use of
while. - Always be careful about accidentally creating infinite loops.
You can now choose between for and
while loops depending on the type
of repetition your program requires.
Ready for the Next Lesson?
Complete the exercises and guessing-game challenge, then mark this lesson as complete.