Python While Loop


What is a while loop and when should you use it?

A while loop repeats code until a given condition stops being true. It checks the condition before each round. If the condition is true, it enters the loop. If it becomes false, the loop ends.

A while loop is useful when:

  • You don’t know how many times a task needs to repeat.

  • You are waiting for a certain event or input.

  • You want to run a loop until a break condition happens.

  • You use counters that change inside the loop.

Where a for loop works well with a fixed range or collection, a while loop fits better with logical conditions, user interactions, waiting states or dynamic updates.

Example:

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

How does the basic syntax of a while loop work?

The pattern is simple:

while condition:
    # repeated code

Python checks the condition before starting each cycle. If the condition is false at the start, the loop does not run even once.

A simple flow:

  1. Check condition → true

  2. Run loop block

  3. Update variables

  4. Go back and check condition again

  5. Stop when condition becomes false

This structure helps build loops that respond to changing values.

How to use counters inside a while loop?

Most while loops use counters. The counter is updated manually inside the loop. Forgetting to update it leads to infinite loops.

Example with counter:

i = 1
while i <= 10:
    print("Step", i)
    i += 1

This pattern appears in almost every basic program that requires repeated actions until a limit is reached.

What are infinite loops and how to avoid them?

An infinite loop runs forever because the condition never becomes false.

Example:

x = 5
while x > 0:
    print(x)

This loop never updates x, so it never stops.

To avoid infinite loops:

  • Always update variables that appear in the condition.

  • Make sure the condition can become false.

  • Double-check logic before running your program.

Sometimes infinite loops are intentional, such as waiting for user input, but even then a break condition must exist.

How do I use break and continue with while loops?

The break statement stops the loop immediately.

Example:

num = 1
while num < 10:
    if num == 5:
        break
    print(num)
    num += 1

The continue statement skips the rest of the block and jumps back to the condition check.

Example:

n = 0
while n < 10:
    n += 1
    if n % 2 == 0:
        continue
    print("Odd:", n)

These controls are important when working with conditions, filtering or interactive loops.

How do I use while loops with user input?

While loops are perfect when you need to keep asking the user for data until something valid is entered.

Example: asking until a correct number is entered

value = int(input("Enter a number bigger than 50: "))

while value <= 50:
    print("Try again.")
    value = int(input("Enter a number bigger than 50: "))

print("Accepted:", value)

This pattern is common in form validation, login attempts and menu-driven applications.

How does a while loop compare with a for loop?

Both loops repeat code, but they serve different tasks.

Use a for loop when:

  • You know how many times you want to repeat.

  • You are looping through a list, string or range.

Use a while loop when:

  • The number of repetitions depends on a condition.

  • Input or external events decide when the loop ends.

  • You need more flexible control over counters.

How to use flags and logical conditions in while loops?

Flags allow the loop to run until the program decides it should stop. This is useful for systems like login flows, menus or processing queues.

Example:

running = True

while running:
    choice = input("Type 'stop' to exit: ")
    if choice == "stop":
        running = False

print("Loop ended.")

Flags make loops easier to manage in larger programs.

How to use nested while loops?

Nested loops are loops inside loops. They help with grid patterns, repeated calculations and table-like structures.

Example:

i = 1
while i <= 3:
    j = 1
    while j <= 3:
        print(i, j)
        j += 1
    i += 1

This structure is often used for pattern printing, multiplying tables or working with matrix-style data.

Real-world example: password retry system

attempts = 0
password = "python123"

while attempts < 3:
    user_input = input("Enter password: ")
    if user_input == password:
        print("Login successful.")
        break
    attempts += 1
else:
    print("Account locked after 3 attempts.")

This example uses attempts, conditions and the else block together.

Real-world example: countdown timer

time_left = 5

while time_left > 0:
    print("Time left:", time_left)
    time_left -= 1

print("Timer ended.")

This shows how while loops handle backward counters.

Real-world example: menu-driven loop

choice = ""

while choice != "4":
    print("1. Add")
    print("2. Edit")
    print("3. View")
    print("4. Exit")
    choice = input("Select: ")

print("Program closed.")

This pattern appears in simple tools, console apps and educational projects.

Summary of the Tutorial

A while loop runs as long as its condition stays true. It is ideal when you don’t know the exact number of repetitions and want the loop to depend on changing values, user input or program logic. With counters, break, continue, flags, nested loops and input-based decisions, while loops become a flexible tool for everything from validation to timers to menu-driven programs. Understanding how conditions change during each cycle is the key to writing safe and predictable while loops.


Practice Questions

  1. Write a program that prints numbers from 1 to 10 using a while loop.

  2. Create a countdown program that starts from 20 and stops at 0.

  3. Ask the user to enter a number greater than 100. Use a while loop to keep asking until they enter a valid number.

  4. Make a login system that allows three attempts. Stop the loop early if the correct password is entered.

  5. Use a while loop to print only even numbers between 1 and 50.

  6. Write a program that keeps adding user-entered numbers until the user types “stop”. Print the total at the end.

  7. Create a menu loop that keeps showing options until the user chooses “Exit”.

  8. Use a while loop to count how many vowels are in a word entered by the user.

  9. Make a multiplication table (for example, table of 7) using a counter-based while loop.

  10. Use nested while loops to print a 3×3 grid of numbers like:
    1 1
    1 2
    1 3
    2 1 ... and so on.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top