The Wayback Machine - https://web.archive.org/web/20250304091430/https://www.geeksforgeeks.org/python-while-loop/
Open In App

Python While Loop

Last Updated : 10 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed.

In this example, the condition for while will be True as long as the counter variable (count) is less than 3. 

Python
# Python example for while loop
count = 0
while (count < 3):
    count = count + 1
    print("Hello Geek")

Output
Hello Geek
Hello Geek
Hello Geek

Let’s take a look at Python While Loop in detail:

while loop Syntax

while expression:
statement(s)

  • condition: This is a boolean expression. If it evaluates to True, the code inside the loop will execute.
  • statement(s): These are the statements that will be executed during each iteration of the loop.

While Loop Flowchart

Python While Loop

While Loop

The while loop will continue running the code block as long as the condition evaluates to True. Each time the loop executes, the condition is checked again. If it is True, the loop continues; if it is False, the loop terminates, and the program moves to the next statement after the loop.

Infinite while Loop in Python

Here, the value of the condition is always True. Therefore, the body of the loop is run infinite times until the memory is full.

Python
age = 28

# the test condition is always True
while age > 19:
    print('Infinite Loop')

Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.

while loop with continue statement

Python Continue Statement returns the control to the beginning of the loop.

Python
# Prints all letters except 'e' and 's'
i = 0
a = 'geeksforgeeks'

while i < len(a):
    if a[i] == 'e' or a[i] == 's':
        i += 1
        continue
        
    print(a[i])
    i += 1

Output
g
k
f
o
r
g
k

while loop with break statement

Python Break Statement brings control out of the loop.

Python
# break the loop as soon it sees 'e'
# or 's'
i = 0
a = 'geeksforgeeks'

while i < len(a):
    if a[i] == 'e' or a[i] == 's':
        i += 1
        break
        
    print(a[i])
    i += 1

Output
g

while loop with pass statement

The Python pass statement to write empty loops. Pass is also used for empty control statements, functions, and classes.

Python
# An empty loop
a = 'geeksforgeeks'
i = 0

while i < len(a):
    i += 1
    pass
  
print('Value of i :', i)

Output
Value of i : 13

while loop with else

As discussed above, while loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed. The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.

Note: The else block just after for/while is executed only when the loop is NOT terminated by a break statement. 

Python
# Python program to demonstrate
# while-else loop

i = 0
while i < 4:
    i += 1
    print(i)
else:  # Executed because no break in for
    print("No Break\n")

i = 0
while i < 4:
    i += 1
    print(i)
    break
else:  # Not executed as there is a break
    print("No Break")

Output
1
2
3
4
No Break

1

Python While Loop – FAQs

How to write while loop in Python?

A while loop in Python is created using the following syntax:

while condition:
# code block to be executed

The loop runs as long as the condition is true.

What are typical use cases for using while loops in Python?

Typical use cases for while loops include:

  • Repeating tasks until a condition is met, such as reading lines from a file.
  • Continuously prompting the user for input until valid data is provided.
  • Running the main loop of a game until the player quits.
  • Polling or continuously checking the status of a resource or condition.

How to control a while loop with break and continue in Python?

break: Exits the loop immediately, regardless of the condition.

while True:
s= input("Enter something (or 'quit' to stop): ")
if s== 'quit':
break
print(f"You entered: {s}")

continue: Skips the rest of the code inside the loop for the current iteration and jumps back to the beginning to re-evaluate the condition.

cnt= 0
while cnt< 10:
cnt+= 1
if cnt% 2 == 0:
continue
print(cnt) # prints only odd numbers

What are the dangers of using a while loop in Python?

The dangers include:

  • Infinite Loops : If the condition never becomes false, the loop will run indefinitely, potentially causing the program to hang.
  • Resource Exhaustion : Continuously running loops can consume system resources, such as memory and CPU, leading to performance issues.
  • Complexity and Readability : While loops can make code harder to read and maintain if not used properly, especially when nested deeply or when the loop conditions are complex.
while True:
print("This will run forever!")

How can we use a while loop to read user input in Python?

You can use a while loop to repeatedly prompt the user for input until a valid response is received:

s= ""
while s.lower() != "exit":
s= input("Enter something (type 'exit' to stop): ")
if s.lower() != "exit":
print(f"You entered: {s}")
print("Goodbye!")

Level up your coding with DSA Python in 90 days! Master key algorithms, solve complex problems, and prepare for top tech interviews. Join the Three 90 Challenge—complete 90% of the course in 90 days and earn a 90% refund. Start your Python DSA journey today!


Next Article

Similar Reads

Difference between for loop and while loop in Python
In this article, we will learn about the difference between for loop and a while loop in Python. In Python, there are two types of loops available which are 'for loop' and 'while loop'. The loop is a set of statements that are used to execute a set of statements more than one time. For example, if we want to print "Hello world" 100 times then we ha
4 min read
Loop Through a List using While Loop in Python
In Python, the while loop is a versatile construct that allows you to repeatedly execute a block of code as long as a specified condition is true. When it comes to looping through a list, the while loop can be a handy alternative to the more commonly used for loop. In this article, we'll explore four simple examples of how to loop through a list us
3 min read
Decrement in While Loop in Python
A loop is an iterative control structure capable of directing the flow of the program based on the authenticity of a condition. Such structures are required for the automation of tasks. There are 2 types of loops presenting the Python programming language, which are: for loopwhile loop This article will see how to decrement in while loop in Python
3 min read
Multiplication Table Using While Loop in Python
Multiplication tables are fundamental in mathematics, serving as the building blocks for more advanced concepts. In Python, we can use various methods to generate multiplication tables, and one versatile tool for this task is the 'while' loop. In this article, we will explore some commonly used and straightforward methods to create multiplication t
3 min read
Python Program to Find the Sum of Natural Numbers Using While Loop
Calculating the Sum of N numbers in Python using while loops is very easy. In this article, we will understand how we can calculate the sum of N numbers in Python using while loop.Calculate Sum of Natural Numbers in Python Using While LoopBelow are some of the examples by which we can see how we can calculate the sum of N numbers in Python:Example
2 min read
How to Kill a While Loop with a Keystroke in Python?
Loops are fundamental structures in Python programming for executing a block of code repeatedly until a certain condition is met. However, there are scenarios where you might want to terminate a while loop prematurely, especially when you want to give the user the ability to interrupt the loop with a keystroke. In this article, we'll explore some s
3 min read
How to Parallelize a While loop in Python?
Parallelizing a while loop in Python involves distributing the iterations of a loop across multiple processing units such as the CPU cores or computing nodes to execute them concurrently. This can significantly reduce the overall execution time of the loop, especially for tasks that are CPU-bound or require heavy computation. In this article, we'll
2 min read
How to Emulate a Do-while loop in Python?
We have given a list of strings and we need to emulate the list of strings using the Do-while loop and print the result. In this article, we will take a list of strings and then emulate it using a Do-while loop. Do while loop is a type of control looping statement that can run any statement until the condition statement becomes false specified in t
3 min read
R - while loop
While loop in R programming language is used when the exact number of iterations of a loop is not known beforehand. It executes the same code again and again until a stop condition is met. While loop checks for the condition to be true or false n+1 times rather than n times. This is because the while loop checks for the condition before entering th
5 min read
Python | Delete items from dictionary while iterating
A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple. Note: In Python 2 dictionary keys were unordered. As of Python 3, they
3 min read