Table of contents
1.
Introduction
2.
What is a while loop in Python?
3.
While Loop Syntax
3.1.
Python
4.
Flowchart of While Loop in Python
5.
Examples of Python While Loop
5.1.
Python
5.2.
User input validation
5.3.
Nested while loops
5.4.
Python
6.
Infinite while Loop in Python
6.1.
Example:
6.2.
Python
6.3.
 
7.
Python While Loop With Break Statement
7.1.
Example:
7.2.
Python
8.
Python While Loop With Continue Statement
8.1.
Example
8.2.
Python
9.
Python While Loop with Pass Statement
9.1.
Python
10.
Python While Loop with Else
10.1.
Python
11.
Single statement while block
11.1.
Syntax
11.2.
Example
11.3.
Python
12.
Frequently Asked Questions
12.1.
What is a while loop example?
12.2.
What is the code in a while loop that returns the output of the given code?
12.3.
What type is a while loop?
12.4.
What happens if the condition in a while loop is always true?
13.
Conclusion
Last Updated: Aug 11, 2025
Easy

While Loop in Python

Introduction

Loops are a fundamental part of programming, enabling repetitive tasks to be automated efficiently. In Python, the while loop is a powerful construct used to execute a block of code repeatedly as long as a given condition remains True. Unlike a for loop, which iterates over a sequence, the while loop is ideal for scenarios where the number of iterations depends on a condition that may change during execution.

While Loop in Python

What is a while loop in Python?

A while loop in Python is a control flow statement that repeatedly executes a block of code as long as a specified condition evaluates to True. It is used when the number of iterations is not predetermined and depends on the dynamic evaluation of a condition during runtime.

While Loop Syntax

The basic syntax of a while loop in Python is:

while condition:
    # code block to be executed


Here, condition is an expression that is evaluated before each iteration of the loop. If the condition is true, the code block inside the loop is executed. This process continues until the condition becomes false.

For example, let's print the numbers from 1 to 5 using a while loop:

  • Python

Python

count = 1

while count <= 5:

   print(count)

   count += 1
You can also try this code with Online Python Compiler
Run Code


Output

1
2
3
4
5


In this example, the variable count is initialized to 1. The while loop continues to run as long as count is less than or equal to 5. Inside the loop, we print the value of count and then increment it by 1 using the += operator. This process repeats until count becomes 6, at which point the condition becomes false, and the loop terminates.

Flowchart of While Loop in Python

A flowchart is a visual representation of the flow of a program. It helps in understanding the logic behind a while loop. Here's a flowchart that illustrates the working of a while loop:

Flowchart of Python While Loop

The flowchart starts with initializing the necessary variables. Then, it checks the loop condition. If the condition is true, the loop body is executed, and the flow goes back to check the condition again. This process continues until the condition becomes false, at which point the loop ends, and the program continues with the next statement after the loop.

Examples of Python While Loop

While loops in Python are versatile and can be used in various scenarios. Let's look at a few more examples to understand the concept better : 

Summing numbers until a condition is met:

  • Python

Python

total = 0
num = 1
while total < 100:
total += num
num += 1
print("The sum is:", total)
You can also try this code with Online Python Compiler
Run Code


Output

The sum is: 105


In this example, we initialize total to 0 and num to 1. The while loop continues to add num to total and increments num by 1 in each iteration until total becomes greater than or equal to 100. Finally, we print the sum.

User input validation

while True:
    user_input = input("Enter a positive number: ")
    if user_input.isdigit() and int(user_input) > 0:
        break
    print("Invalid input. Please try again.")
print("You entered:", user_input)


Here, we use a while loop to repeatedly prompt the user for input until they enter a valid positive number. The loop continues until the break statement is encountered, which happens when the user enters a valid input.

Nested while loops

  • Python

Python

i = 1

while i <= 3:

   j = 1

   while j <= 3:

       print(i, j)

       j += 1

   i += 1
You can also try this code with Online Python Compiler
Run Code


Output

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3


In this example, we use nested while loops to generate all possible combinations of numbers from 1 to 3. The outer loop iterates over the values of i, while the inner loop iterates over the values of j for each value of i.

Infinite while Loop in Python

An infinite while loop is a loop that never ends because its condition always evaluates to True. Such loops are useful in scenarios like continuously monitoring input, running a server, or creating event-driven programs. However, they must be carefully controlled to avoid unintended infinite execution.

Example:

  • Python

Python

while True:
user_input = input("Enter 'exit' to stop the loop: ")
if user_input.lower() == 'exit':
print("Loop stopped.")
break
else:
print(f"You entered: {user_input}")
You can also try this code with Online Python Compiler
Run Code

 

Python While Loop With Break Statement

  • The break statement is used to exit the loop prematurely, even if the condition is still true.
     
  • When break is encountered, the program immediately exits the loop and continues with the next statement after the loop.

Example:

  • Python

Python

count = 0

while count < 5:

   count += 1

   if count == 3:

       break

   print(count)
You can also try this code with Online Python Compiler
Run Code


Output

1
2


In this example, the loop starts with count equal to 0. Inside the loop, count is incremented by 1. When count becomes 3, the break statement is executed, and the loop is terminated. As a result, only the numbers 1 and 2 are printed.

Python While Loop With Continue Statement

  • The continue statement is used to skip the rest of the current iteration and move to the next iteration of the loop.
     
  • When continue is encountered, the program skips the remaining code in the current iteration and proceeds to the next iteration.

Example

  • Python

Python

count = 0

while count < 5:

   count += 1

   if count == 3:

       continue

   print(count)
You can also try this code with Online Python Compiler
Run Code


Output

1
2
4
5


In this example, when count becomes 3, the continue statement is executed. It skips the print statement for that iteration and moves to the next iteration. As a result, the number 3 is not printed.

Python While Loop with Pass Statement

The pass statement in Python is a placeholder that does nothing. It can be used inside a while loop when a block of code is required syntactically, but you do not want to execute any action. This is useful when you need to build a loop structure but haven't defined its actions yet.

  • Python

Python

i = 0
while i < 5:
i += 1
if i == 3:
pass # Do nothing when i is 3
else:
print(i)
You can also try this code with Online Python Compiler
Run Code

 

In this example, the loop will print numbers from 1 to 5, but when i equals 3, the pass statement ensures that no action is taken, and the loop continues.

Python While Loop with Else

In Python, a while loop can be followed by an else block. The else block will be executed only if the loop terminates normally (i.e., the loop condition becomes False). If the loop is terminated by a break statement, the else block will not run.

  • Python

Python

i = 0
while i < 5:
print(i)
i += 1
else:
print("Loop finished without a break.")
You can also try this code with Online Python Compiler
Run Code

 

In this example, the loop will print numbers from 0 to 4. Once the condition i < 5 becomes False, the else block is executed, printing "Loop finished without a break."

Single statement while block

In Python, if the body of a while loop consists of a single statement, you can write it on the same line as the while condition. This is known as a single statement while block.

Syntax

while condition: statement

Example

  • Python

Python

count = 1

while count <= 5: print(count); count += 1
You can also try this code with Online Python Compiler
Run Code


Output

1
2
3
4
5


In this example, the print statement and the increment of count are written on the same line as the while condition. The semicolon (;) is used to separate multiple statements on the same line.

However, it's generally recommended to use a proper indented block for better readability and maintainability, especially if the loop body consists of multiple statements or if the loop is more complex.

Example with an indented block:

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


This version of the code achieves the same result but is more readable and easier to understand.

Single statement while blocks can be useful for simple and concise loops, but it's important to prioritize code clarity and follow good coding practices. If the loop body becomes more complex or requires multiple statements, it's better to use an indented block for better organization and readability.

Frequently Asked Questions

What is a while loop example?

A while loop repeatedly executes a block of code as long as the condition is True. Example:

i = 0
while i < 5:
   print(i)
   i += 1

 

What is the code in a while loop that returns the output of the given code?

The code in a while loop iterates until a condition is met, such as:

i = 0
while i < 5:
   print(i)
   i += 1

 

This prints 0, 1, 2, 3, 4.

What type is a while loop?

A while loop is a conditional loop that executes a block of code based on a condition being True, and stops when the condition becomes False.

What happens if the condition in a while loop is always true?

Suppose the condition in a while loop is always true. In that case, it will result in an infinite loop, and the program will keep executing the loop body indefinitely unless there is a break statement or some other way to exit the loop.

Conclusion

In this article, we have learned about while loops in Python. We explained the syntax of while loops, how to use them to repeat a block of code based on a condition, and how to control the flow of execution using break and continue statements. We also discussed the differences between while loops and for loops and saw examples of using while loops in various scenarios. 

Recommended Readings:

 

 

 

Live masterclass