Home Course Roadmap
Lesson 26 · Control Flow Beginner

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.

40–50 minutes
Control Flow
Python Foundations
0%

What You Will Learn

  • Understand how while loops work.
  • Write loops controlled by conditions.
  • Build counter-controlled loops.
  • Use break and continue.
  • Validate user input using loops.
  • Understand and prevent infinite loops.
  • Use while...else.
  • Build practical programs using while.
01

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.

Basic example
count = 1

while count <= 5:
    print(count)
    count += 1
Output
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.

Core Idea

A while loop asks: "Is the condition still true?" If yes, execute the loop body again.

02

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.

03

Basic Syntax

The basic structure of a Python while loop is:

Syntax
while condition:
    # code to execute

The condition must produce a Boolean result: True or False.

Example
number = 1

while number <= 3:
    print("Hello")
    number += 1
Output
Hello
Hello
Hello

The variable is updated during every iteration so that the condition eventually becomes false.

04

The Loop Condition

The condition controls whether the loop continues.

Condition example
temperature = 30

while temperature > 25:
    print("Temperature is high")
    temperature -= 1
Output
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

  1. Check the condition.
  2. If it is true, run the body.
  3. Update the relevant value.
  4. Check the condition again.
  5. Stop when the condition becomes false.
05

Counter-Controlled Loops

One of the simplest uses of a while loop is counting.

Counting from 1 to 5
count = 1

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

Here, count is called a loop control variable.

Three Important Parts

A counter-controlled loop normally contains:

  1. An initial value.
  2. A condition.
  3. An update operation.
06

Updating the Variable

One of the most important rules of a while loop is to make sure the condition can eventually become false.

Incrementing
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

Example
number = 2

while number <= 10:
    print(number)
    number += 2
Output
2
4
6
8
10
07

Counting Backwards

A while loop can also count downward.

Countdown
count = 5

while count >= 1:
    print(count)
    count -= 1

print("Go!")
Output
5
4
3
2
1
Go!

The operator -= decreases the value of count by one during each iteration.

08

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.

User-controlled loop
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

Simple menu
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.

09

Input Validation with while

A loop can force a program to continue asking for input until the user provides valid information.

Age validation
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 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)
Why This Matters

Input validation prevents invalid data from entering the rest of your program.

10

Using break

The break statement immediately terminates the loop.

Example
number = 1

while number <= 10:

    if number == 5:
        break

    print(number)
    number += 1
Output
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.

11

Using continue

The continue statement skips the rest of the current iteration and moves to the next iteration.

Example
number = 0

while number < 6:

    number += 1

    if number == 3:
        continue

    print(number)
Output
1
2
4
5
6

When the number becomes 3, continue skips the print() statement for that iteration.

Important

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.

12

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.

Example
count = 1

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

else:
    print("Loop finished.")
Output
1
2
3
Loop finished.

When break Is Used

Example
count = 1

while count <= 5:

    if count == 3:
        break

    print(count)
    count += 1

else:
    print("Loop finished.")
Output
1
2

Because break terminated the loop, the else block did not run.

13

Nested while Loops

A nested loop is a loop placed inside another loop.

Example
row = 1

while row <= 3:

    column = 1

    while column <= 3:
        print(row, column)
        column += 1

    row += 1
Output
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.

Be Careful

Nested loops can become difficult to understand if the control variables are not managed clearly. Give each loop its own appropriate variable.

14

Infinite Loops

An infinite loop is a loop that never reaches a condition that makes it stop.

Problematic example
number = 1

while number <= 5:
    print(number)

This loop never changes number. Therefore, number <= 5 remains true forever.

Correct Version

Fixed example
number = 1

while number <= 5:
    print(number)
    number += 1
Safety Rule

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:

Intentional loop
while True:

    command = input("Enter command: ")

    if command == "exit":
        break

In this pattern, break provides the exit condition.

15

Practical Real-World Examples

Example 1 — Countdown Timer Logic

Countdown
seconds = 5

while seconds > 0:
    print("Seconds remaining:", seconds)
    seconds -= 1

print("Time's up!")
Output
Seconds remaining: 5
Seconds remaining: 4
Seconds remaining: 3
Seconds remaining: 2
Seconds remaining: 1
Time's up!

Example 2 — Password Attempts

Password system
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

Menu-driven program
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

Search example
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)
Output
Found: True
16

Common Mistakes

1. Forgetting the Colon

Incorrect
while count < 5
    print(count)

Python requires a colon after the loop condition.

2. Forgetting to Update the Control Variable

Problem
count = 1

while count <= 5:
    print(count)

The value of count never changes, so the loop never ends.

3. Updating in the Wrong Direction

Problem
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

Incorrect
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

Think Carefully

If continue executes before the control variable is updated, the loop may return to the same condition forever.

17

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.

18

Mini Challenge — Number Guessing Game

Build a simple number guessing game using a while loop.

Your program should:

  1. Choose a secret number.
  2. Ask the user to guess it.
  3. Tell the user whether the guess is too high or too low.
  4. Continue asking until the correct number is entered.
  5. Count the number of attempts.
  6. Display a success message at the end.
Starter Code
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.

Challenge Goal

Try building the program yourself before looking for alternative solutions. Focus on understanding why the loop condition changes after every guess.

19

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?

20

Lesson Summary

A Python while loop repeatedly executes code as long as its condition remains true.

  • A while loop 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.
  • break immediately terminates a loop.
  • continue skips the current iteration.
  • while...else can detect normal completion.
  • Nested while loops can solve more complex problems.
  • Input validation is a practical use of while.
  • Always be careful about accidentally creating infinite loops.
You've Mastered Another Control Flow Tool

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.