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")
OutputHello 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

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
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
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)
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")
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!")
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!")
Similar Reads
Python While Loop
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)
5 min read
Python Do While Loops
In Python, there is no construct defined for do while loop. Python loops only include for loop and while loop but we can modify the while loop to work as do while as in any other languages such as C++ and Java. In Python, we can simulate the behavior of a do-while loop using a while loop with a cond
6 min read
Python While Else
Python is easy to understand and a robust programming language that comes with lots of features. It offers various control flow statements that are slightly different from those in other programming languages. The "while-else" loop is one of these unique constructs. In this article, we will discuss
6 min read
Python - Itertools.takewhile()
The itertools is a module in Python having a collection of functions that are used for handling iterators. They make iterating through the iterables like lists and strings very easy. One such itertools function is takewhile(). Note: For more information, refer to Python Itertools takewhile() This al
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
3 min read
Python For Loops
Python For Loops are used for iterating over a sequence like lists, tuples, strings, and ranges. For loop allows you to apply the same operation to every item within loop. Using For Loop avoid the need of manually managing the index.For loop can iterate over any iterable object, such as dictionary,
6 min read
Python Else Loop
Else with loop is used with both while and for loop. The else block is executed at the end of loop means when the given loop condition is false then the else block is executed. So let's see the example of while loop and for loop with else below. Else with While loop Consider the below example. C/C++
3 min read
Looping Techniques in Python
Python supports various looping techniques by certain inbuilt functions, in various sequential containers. These methods are primarily very useful in competitive programming and also in various projects that require a specific technique with loops maintaining the overall structure of code. A lot of
6 min read
Python Nested Loops
In Python programming language there are two types of loops which are for loop and while loop. Using these loops we can create nested loops in Python. Nested loops mean loops inside a loop. For example, while loop inside the for loop, for loop inside the for loop, etc. Python Nested Loops Syntax:Out
9 min read
Python Variables
In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read