View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Understanding While Loop in Python with Examples

Updated on 29/05/20255,885 Views

Loops are essential when you need to run a set of instructions repeatedly. One of the most commonly used loops in Python is the while loop. The while loop in Python runs a block of code as long as a given condition is true.

In this article, we will explore how this loop works with real-world examples, from basic to advanced. We will also understand when and why to use it over other loops like for. You will also learn how the loop handles infinite conditions and how it differs from the for loop in Python. Whether you're a beginner or someone looking to brush up your Python basics, this article will help you use the while loop efficiently and correctly.

Pursue our Software Engineering courses to get hands-on experience!

What is While Loop in Python?

The while loop in Python is used to execute a block of code repeatedly as long as a specific condition remains true. Unlike a for loop, which runs for a predefined number of times, a while loop continues until the given condition becomes false.

This makes it ideal for scenarios where the number of iterations isn’t known in advance. You can use it for checking sensor values, reading files until EOF, or repeating user input requests until valid data is entered.

Syntax of Python While Loop 

Before writing real-world examples, it's important to understand the correct syntax of a while loop in Python. The structure is simple and easy to remember. The loop starts with the keyword while, followed by a condition. As long as the condition is True, the loop body will keep executing.

Below is the general syntax with a short example to help you understand better.

while condition:
# block of code

Take your skills to the next level with these top programs:

Now let’s see a working example that uses this syntax.

Example: Print Numbers from 1 to 3

# Initialize a counter variable
count = 1

# Loop continues while count is less than or equal to 5
while count <= 5:
print("Current count:", count) # Print current value
count += 1 # Increment the counter

Output:

Current count: 1

Current count: 2

Current count: 3

Current count: 4

Current count: 5

Explanation:

  • The variable count starts at 1.
  • The loop condition count <= 5 is checked before each iteration.
  • If the condition is true, it prints the current count and increments the value by 1.
  • Once count becomes 6, the condition turns false, and the loop stops.

This is the basic structure of how a while loop works in Python. It is simple but powerful and can be adapted for complex tasks too.

Must Explore: Nested for loop in Python

While Loop in Python Examples

Let’s look at different examples of the while loop in Python to understand how it works in real scenarios. We will begin with a basic example and move on to intermediate and advanced use cases.

Basic Level: Print Even Numbers from 1 to 10

This example demonstrates how to use a while loop to print even numbers within a range. It uses a simple condition and an increment statement.

# Initialize a counter variable
count = 1

# Loop continues while count is less than or equal to 5
while count <= 5:
print("Current count:", count) # Print current value
count += 1 # Increment the counter

Output:

Even number: 2

Even number: 4

Even number: 6

Even number: 8

Even number: 10

Explanation:

  • The loop starts with num = 1.
  • Each time, it checks if the number is divisible by 2.
  • If true, it prints the number.
  • The loop stops after reaching 10.

Intermediate Level: Validate User Input (Password Check)

This example shows how to keep asking the user for input until they enter the correct password. This is a common use case where you don’t know how many tries the user might take.

# Correct password to match
correct_password = "python123"

# Initialize user input
user_input = ""

# Keep prompting until input matches the correct password
while user_input != correct_password:
user_input = input("Enter the password: ")

print("Access Granted!")

Output:

Enter the password: python12

Enter the password: python 123

Enter the password: python123

Access Granted!

Explanation:

  • The loop keeps running as long as the input is incorrect.
  • As soon as the correct password is entered, the loop exits.
  • This is useful for login or authentication checks.

Also read the Top 43 Pattern Programs in Python to Master Loops and Recursion article!

Advanced Level: Simulate Countdown Timer (With Delay)

This example uses a while loop to simulate a countdown timer. It also uses the time module to pause execution between iterations.

import time  # Importing time module

# Start countdown from 5
countdown = 5

# Loop until countdown reaches 0
while countdown > 0:
print("Timer:", countdown)
time.sleep(1) # Pause for 1 second
countdown -= 1 # Decrement the counter

print("Time's up!")

Output:

Timer: 5

Timer: 4

Timer: 3

Timer: 2

Timer: 1

Time's up!

Explanation:

  • The loop runs as long as countdown is greater than 0.
  • After each print, it pauses for one second using sleep().
  • This simulates a timer, useful in games, reminders, or delays.

Infinite While Loop in Python

An infinite while loop in Python is a loop that never stops running unless you explicitly break it. This happens when the loop condition always evaluates to True. These loops are useful in cases like waiting for user input, running servers, or background tasks.

Let’s see how to create one and how to control it using a break statement.

Example: Infinite Loop That Waits for a Keyword to Exit

# Start an infinite loop
while True:
# Ask the user to enter a command
user_input = input("Type 'exit' to stop the loop: ")

# Check if the input is 'exit'
if user_input.lower() == 'exit':
print("Exiting the loop.")
break # Exit the loop
else:
print("You typed:", user_input)

Output:

Type 'exit' to stop the loop: hello

You typed: hello

Type 'exit' to stop the loop: python

You typed: python

Type 'exit' to stop the loop: exit

Exiting the loop.

Explanation:

  • while True: creates an infinite loop because True never becomes false.
  • It continuously asks the user for input.
  • If the user types "exit" (case-insensitive), the break statement ends the loop.
  • Otherwise, it keeps running and prints what the user typed.

Note:

If you don’t include a break statement or a condition that eventually turns False, the loop will run forever and may freeze your program.

Best Practices:

  • Always include an exit condition inside an infinite loop.
  • Use Ctrl + C in the terminal to forcefully stop an infinite loop if needed.

Also explore Python's do-while Loop article!

While Loop with Continue Statement

In Python, the continue statement is used inside a while loop to skip the current iteration and move to the next one. This helps in cases where you want to ignore certain values or conditions without exiting the loop entirely.

Let’s understand this with a simple and practical example.

Example: Print Numbers from 1 to 10 but Skip Multiples of 3

# Start counting from 1
num = 1

# Loop until num exceeds 10
while num <= 10:
# Skip numbers divisible by 3
if num % 3 == 0:
num += 1 # Increment before continue to avoid infinite loop
continue # Skip printing this number

print("Number:", num)
num += 1 # Increment num for the next iteration

Output:

Number: 1

Number: 2

Number: 4

Number: 5

Number: 7

Number: 8

Number: 10

Explanation:

  • The loop starts with num = 1 and goes up to 10.
  • If num is a multiple of 3, the loop skips the print statement.
  • Notice we increment num before the continue to prevent an infinite loop.
  • Numbers divisible by 3 (3, 6, 9) are not printed.
  • All other numbers are displayed.

Using continue helps you control which iterations to process and which to skip. It improves code clarity by avoiding nested conditions inside the while loop in Python.

While Loop with Break Statement

In Python, the break statement is used inside a while loop to stop the loop immediately, regardless of the loop’s original condition. This lets you exit the loop when a specific event or condition occurs.

Using break helps you control the flow more precisely, especially when you want to terminate the loop early.

Example: Stop the Loop When Number Reaches 5

# Initialize the counter
num = 1

# Start the while loop
while True:
print("Current number:", num)

# Stop the loop when num reaches 5
if num == 5:
print("Reached 5, exiting the loop.")
break # Exit the loop immediately

num += 1 # Increment the counter

Output:

Current number: 1

Current number: 2

Current number: 3

Current number: 4

Current number: 5

Reached 5, exiting the loop.

Explanation:

  • The loop is infinite (while True:) but uses break to stop when num equals 5.
  • Each iteration prints the current value of num.
  • When num is 5, the break statement stops the loop.
  • The message confirms the loop exit.
  • The counter increments by 1 each time before checking the condition.

While Loop with Pass Statement

The pass statement in Python acts as a placeholder inside a while loop. It does nothing but allows the loop to run without errors when no action is needed in a particular part of the code.

This is helpful when you plan to add code later or want to create a loop that intentionally does nothing in some cases.

Example: Using Pass to Create an Empty While Loop That Runs Three Times

# Initialize the counter
count = 0

# Run the loop while count is less than 3
while count < 3:
pass # Placeholder: no action is performed here

# Increment the counter
count += 1

print("Loop finished after 3 iterations.")

Output:

Loop finished after 3 iterations.

Explanation:

  • The loop runs while count is less than 3.
  • Inside the loop, pass does nothing but avoids syntax errors.
  • The counter increments each iteration, ensuring the loop ends.
  • After 3 iterations, the loop finishes and prints the message.

Must Read: Break Pass and Continue Statement in Python

While Loop with Else

In Python, a while loop can have an optional else block. The else block executes only when the while loop condition becomes false. However, if the loop exits due to a break statement, the else block is skipped.

This feature allows you to run specific code after the loop completes normally.

Example: Using Else with While Loop to Confirm Completion

# Initialize counter
num = 1

# Loop while num is less than or equal to 5
while num <= 5:
print("Number:", num)
num += 1
else:
print("Loop finished without interruption.")

Output:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

Loop finished without interruption.

Explanation:

  • The while loop runs until num exceeds 5.
  • Each number is printed in the loop.
  • When num becomes 6, the loop condition is false.
  • Since the loop ends normally, the else block runs and prints the completion message.
  • If the loop had a break inside, the else block would be skipped.

Also read the Reverse String in Python article!

When Should You Use the While Loop in Python?

The while loop in Python is best suited for scenarios where you want to repeat a block of code until a certain condition changes. Unlike for loops, which iterate over sequences, while loops work well when the number of iterations is unknown beforehand.

Consider an example where you keep doubling a number until it exceeds a limit.

Example: Double a Number Until It Becomes Greater Than 100

# Initialize the number
number = 1

# Loop until number is greater than 100
while number <= 100:
print("Current number:", number)

# Double the number each time
number *= 2

print("Loop ended as the number exceeded 100.")

Output:

Current number: 1

Current number: 2

Current number: 4

Current number: 8

Current number: 16

Current number: 32

Current number: 64

Loop ended as the number exceeded 100.

Explanation:

  • The loop starts with number as 1.
  • It prints the current value of number in each iteration.
  • The number doubles every time (number *= 2).
  • The loop runs while number is less than or equal to 100.
  • When number becomes 128, the condition fails, and the loop stops.
  • Finally, it prints a message indicating the loop ended.

In short, use Python While Loop when:

  • The loop depends on a changing condition.
  • The number of iterations can’t be predicted.
  • You want to repeat until a threshold is met or exceeded.
  • Real-time or dynamic data controls the loop’s execution.

Difference Between While and For Loop in Python

Both while and for loops allow repetition in Python, but they serve different purposes. Understanding their differences helps you choose the right loop based on the problem you want to solve.

Below is a detailed comparison between the two loops:

Aspect

While Loop

For Loop

Purpose

Runs as long as a condition remains true.

Iterates over a sequence or iterable directly.

Control

Condition checked before each iteration.

Iterates through items or a range automatically.

Use Case

When the number of iterations is unknown.

When the number of iterations is known or fixed.

Syntax

while condition:

    # code

for item in iterable:

    # code

Possibility of Infinite Loop

High if the condition never becomes false.

Low, since it iterates over a finite iterable.

Modification during Loop

You manually update the condition variable inside the loop.

Loop variable updates automatically each iteration.

When to use

When loop continuation depends on dynamic conditions.

When looping through elements or fixed counts.

Example

while x < 5:

    x += 1

for x in range(5):

    print(x)

Must read the Exception Handling in Python article!

Conclusion

In this article, we explored the while loop in Python, a fundamental tool for repeating code based on conditions. We learned how the while loop runs until its condition becomes false. This makes it powerful for tasks where the number of repetitions is not fixed.

We also examined various practical examples, from basic to advanced levels, including how to use control statements like break, continue, and pass within the while loop. Understanding these helps you control loop execution efficiently.

FAQs

1. What is the main advantage of using a while loop in Python?

The primary advantage of a while loop in Python is its ability to run based on a condition rather than a fixed count. This flexibility allows you to repeat code until a specific dynamic event occurs, making it ideal for situations where the number of iterations is unknown.

2. Can you use multiple conditions in a while loop in Python?

Yes, you can use multiple conditions in a while loop using logical operators like and, or, and not. This lets you create complex criteria for loop execution. For example, while x < 10 and y != 0: runs only when both conditions hold true.

3. How does the while loop differ from recursion in Python?

While loops repeat code using iteration, whereas recursion repeats by calling a function within itself. The while loop is often more memory-efficient and easier to debug. Recursion is better for problems naturally defined by smaller subproblems, like tree traversal.

4. Is it possible to use else with break in a while loop?

Yes. When a while loop completes normally without hitting a break statement, the else block runs. If the loop breaks early, the else block is skipped. This feature helps detect whether a loop ended naturally or was interrupted.

5. How can you safely avoid infinite loops in Python?

To prevent infinite loops, ensure the loop’s condition eventually becomes false. You should update variables involved in the condition inside the loop. Also, using timeout counters or input validation can help stop the loop if unexpected behavior occurs.

6. Can a while loop be nested inside another loop in Python?

Absolutely. You can nest a while loop inside another while loop or a for loop. Nested loops are useful for working with multi-dimensional data or complex iteration patterns. However, keep track of each loop’s condition to avoid logical errors or infinite loops.

7. What happens if the condition in a while loop is initially false?

If the condition in a while loop in Python is false at the start, the loop’s body never executes. The program immediately moves to the next statement after the loop. This behavior is different from a do-while loop found in some other languages.

8. Can the while loop in Python iterate over a list or other iterable?

No, the while loop itself does not iterate over items like a for loop. However, you can manually control the index or pointer inside the loop to traverse a list or iterable. For example, use an index variable and increment it in each iteration.

9. How can you use a while loop for user input validation?

A while loop is perfect for input validation because it can repeatedly ask the user until valid data is entered. For instance, use a loop with a condition checking the input format or range and continue prompting the user until the input meets requirements.

10. Are there performance differences between while and for loops in Python?

For loops are generally faster for iterating over sequences since Python optimizes them internally. While loops offer more flexibility but may require extra care to manage conditions. For most cases, the difference is negligible, but for large data, using for loops is often preferable.

11. How do break and continue improve while loop control?

The break statement immediately ends the loop, useful when you want to stop early based on a condition. The continue statement skips the rest of the current iteration and moves to the next one. Together, they make the while loop in Python more powerful and adaptable.

image

Take our Free Quiz on Python

Answer quick questions and assess your Python knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.