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

Python While Loop

Last Updated : 26 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
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.

Syntax of while loop in Python

while expression:
statement(s)

Flowchart of Python While Loop

Python While Loop

While loop falls under the category of indefinite iteration. Indefinite iteration means that the number of times the loop is executed isn’t specified explicitly in advance. 

Statements represent all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements. When a while loop is executed, expr is first evaluated in a Boolean context and if it is true, the loop body is executed. Then the expr is checked again, if it is still true then the body is executed again and this continues until the expression becomes false.

Difference between Python For Loop and Python While Loop

The main difference between Python For Loop Versus Python While Loop is that Python for loop is usually used when the number of iterations is known, whereas Python while loop is used when the number of iterations is unknown

Python While Loop

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

Python
# Python program to illustrate
# while loop
count = 0
while (count < 3):
    count = count + 1
    print("Hello Geek")

Output
Hello Geek
Hello Geek
Hello Geek

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')

Control Statements in Python with Examples

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.

Python 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('Current Letter :', a[i])
    i += 1

Output
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k

Python while loop with a 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('Current Letter :', a[i])
    i += 1

Output
Current Letter : g

Python while loop with a 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

Sentinel Controlled Statement

In this, we don’t use any counter variable because we don’t know how many times the loop will execute. Here user decides how many times he wants to execute the loop. For this, we use a sentinel value. A sentinel value is a value that is used to terminate a loop whenever a user enters it, generally, the sentinel value is -1.

Python while loop with user input

Here, It first asks the user to input a number. if the user enters -1 then the loop will not execute, i.e.

  • The user enters 6 and the body of the loop executes and again asks for input
  • Here user can input many times until he enters -1 to stop the loop
  • User can decide how many times he wants to enter input
Python
a = int(input('Enter a number (-1 to quit): '))

while a != -1:
    a = int(input('Enter a number (-1 to quit): '))

Output:

Image

Output Screen Image

While loop with Boolean values

One common use of boolean values in while loops are to create an infinite loop that can only be exited based on some condition within the loop. 

Example:

In this example, we initialize a counter and then use an infinite while loop (True is always true) to increment the counter and print its value. We check if the counter has reached a certain value and if so, we exit the loop using the break statement.

Python
# Initialize a counter
count = 0

# Loop infinitely
while True:
    # Increment the counter
    count += 1
    print(f"Count is {count}")

    # Check if the counter has reached a certain value
    if count == 10:
        # If so, exit the loop
        break

# This will be executed after the loop exits
print("The loop has ended.")

Output
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Count is 6
Count is 7
Count is 8
Count is 9
Count is 10
The loop has ended.

Python while loop with Python list

In this example, we have run a while loop over a list that will run until there is an element present in the list.

Python
# checks if list still
# contains any element
a = [1, 2, 3, 4]

while a:
    print(a.pop())

Output
4
3
2
1

Single statement while block

Just like the if block, if the while block consists of a single statement we can declare the entire loop in a single line. If there are multiple statements in the block that makes up the loop body, they can be separated by semicolons (;). 

Python
# Python program to illustrate
# Single statement while block
count = 0
while (count < 5):
    count += 1
    print("Hello Geek")

Output
Hello Geek
Hello Geek
Hello Geek
Hello Geek
Hello Geek

Python While Loop Exercise Questions

Below are two exercise questions on Python while loop. We have covered 2 important exercise questions based on the bouncing ball program and the countdown program.

Q1. While loop exercise question based on bouncing ball problem

Python
initial_height = 10 
bounce_factor = 0.5 
height = initial_height
while height > 0.1:  
    print("The ball is at a height of", height, "meters.")
    height *= bounce_factor  
print("The ball has stopped bouncing.")

Output

The ball is at a height of 10 meters.
The ball is at a height of 5.0 meters.
The ball is at a height of 2.5 meters.
The ball is at a height of 1.25 meters.
The ball is at a height of 0.625 meters.
The ball is at a height of 0.3125 meters.
The ball is at a height of 0.15625 meters.
The ball has stopped bouncing.

Q2. Simple while-loop exercise code to build countdown clock

Python
countdown = 10
while countdown > 0:
    print(countdown)
    countdown -= 1
print("Blast off!")

Output

10
9
8
7
6
5
4
3
2
1
Blast off!

Python While Loop – FAQs

How do we create a 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:
user_input = input("Enter something (or 'quit' to stop): ")
if user_input == 'quit':
break
print(f"You entered: {user_input}")

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.

counter = 0
while counter < 10:
counter += 1
if counter % 2 == 0:
continue
print(counter) # 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:

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


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
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
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
When not to use Recursion while Programming in Python?
To recurse or not to recurse, that is the question. We all know about the fun we have with recursive functions. But it has its own set of demerits too, one of which is going to be explained in this article to help you choose wisely. Say, we need to create a function which when called needs to print the data in a linked list. This can be done in 2 w
3 min read
How to use while True in Python
In this article, we will discuss how to use while True in Python. While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever. Example: While Loop with True C/C++ Code # Python program to demonstrate # while loop with True while True: pass If we run
2 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 the "while-else" loop in detail with examples. Wha
6 min read
Handling Access Denied Error Occurs While Using Subprocess.Run in Python
In Python, the subprocess module is used to run new applications or programs through Python code by creating new processes. However, encountering an "Access Denied" error while using subprocess.run() can be problematic. This error arises due to insufficient permissions for the user or the Python script to execute the intended command. In this artic
5 min read
How to fix "error 403 while installing package with Python PIP"?
When working with Python, pip is the go-to tool for managing packages. However, encountering a "403 Forbidden" error can be frustrating. This error typically indicates that the server refuses to fulfill the request, often due to permissions or access restrictions. In this article, we'll delve into the causes of this error and explore various soluti
4 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 condition that is initially True and then break out of
6 min read
How to Disable Logging While Running Unit Tests in Python Django
It is never necessary to log everything while testing because it may flood the terminal with unnecessary log messages. These logs are useful during development but can be distracting when focusing on the actual test results. Disabling logging during unit tests can make our output cleaner and easier to understand. There are different ways to disable
4 min read
Loops in Python - For, While and Nested Loops
Python programming language provides two types of Python loopshecking time. In this article, we will look at Python loops and understand their working with the help of examp - For loop and While loop to handle looping requirements. Loops in Python provides three ways for executing the loops. While all the ways provide similar basic functionality, t
11 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
How to preserve Function Metadata while using Decorators?
Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it.Note: For more information, refer Decorators in Python How to preserve Metadata? This
2 min read
How to skip rows while reading csv file using Pandas?
Python is a good language for doing data analysis because of the amazing ecosystem of data-centric python packages. Pandas package is one of them and makes importing and analyzing data so much easier. Here, we will discuss how to skip rows while reading csv file. We will use read_csv() method of Pandas library for this task. Syntax: pd.read_csv(fil
3 min read
7 Mistakes You Should Avoid While Building a Django Application
Django...We all know the popularity of this Python framework. Django has become the first choice of developers to build their web applications. It is a free and open-source Python framework. Django can easily solve a lot of common development challenges. It allows you to build flexible and well-structured web applications. A lot of common features
6 min read
How to not get caught while web scraping ?
In this article, we are going to discuss how to not get caught while web scraping. Let's look at all such alternatives in detail: Robots.txtIt is a text file created by the webmaster which tells the search engine crawlers which pages are allowed to be crawled by the bot, so it is better to respect robots.txt before scraping.Example: Here GFG's robo
5 min read
Protecting sensitive information while deploying Django project
There will be a lot of sensitive information in our Django project resided in the settings.py, or local variables containing sensitive information or the POST request made using forms. So while deploying a Django project we always have to make sure they are protected especially the repositories that are publicly available. When a project is deploye
3 min read
Pyspark dataframe: Summing column while grouping over another
In this article, we will discuss how to sum a column while grouping another in Pyspark dataframe using Python. Let's create the dataframe for demonstration: C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sql import SparkSession # creating sparksession and giving an app name spark = SparkSe
4 min read
How to Remove Index Column While Saving CSV in Pandas
In this article, we'll discuss how to avoid pandas creating an index in a saved CSV file. Pandas is a library in Python where one can work with data. While working with Pandas, you may need to save a DataFrame to a CSV file. The Pandas library includes an index column in the output CSV file by default. Further in the article, we'll understand the d
3 min read
PyQt5 - How to automate Progress Bar while downloading using urllib?
PyQt5 is one of the emerging GUI libraries in terms of developing Python GUI Desktop apps. It has rich and robust functionality which ensures production quality apps. Learning PyQt5 library is an add-on to your knowledge. You can develop your consumer quality, highly professional apps. In this article, we will learn how to automate the Progress Bar
3 min read
Avoid these mistakes while preparing for the CAT Exam
The CAT exam is arguably the most important exam in India for students wanting to secure the coveted MBA seats in various management institutes of the country. This is obvious from the high level of competition with more than two lakh candidates competing for seats in various MBA programs such as Finance, Marketing, Operations, etc. and only 11 can
6 min read
Using Else Conditional Statement With For loop in Python
Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated b
2 min read
Print first m multiples of n without using any loop in Python
Given n and m, print first m multiples of a m number without using any loops in Python. Examples: Input : n = 2, m = 3 Output : 2 4 6 Input : n = 3, m = 4 Output : 3 6 9 12 We can use range() function in Python to store the multiples in a range. First we store the numbers till m multiples using range() function in an array, and then print the array
3 min read
Python | Using for loop in Flask
Prerequisite: HTML Basics, Python Basics, Flask It is not possible to write front-end course every time user make changes in his/her profile. We use a template and it generates code according to the content. Flask is one of the web development frameworks written in Python. Through flask, a loop can be run in the HTML code using jinja template and a
3 min read
Understanding for-loop in Python
A Pythonic for-loop is very different from for-loops of other programming language. A for-loop in Python is used to loop over an iterator however in other languages, it is used to loop over a condition. In this article, we will take a deeper dive into Pythonic for-loop and witness the reason behind this dissimilarity. Let's begin by familiarizing o
6 min read
Do loop in Postgresql Using Psycopg2 Python
In this article, we use psycopg2 to loop through all data points using psycopg2 function in Python. We will first connect our PostgreSQL database using psycopg2.connect method, and pass the connection parameters such as the host, database, user, and password. Then we will create a cursor using the conn.cursor method. The cur.execute method, passes
4 min read
Python: Map VS For Loop
Map in Python : Map is used to compute a function for different values 'in a single line of code ' . It takes two arguments, first is function name, that is defined already and the other is list, tuple or any other iterables . It is a way of applying same function for multiple numbers . It generates a map object at a particular location . It works
3 min read
Ways to increment Iterator from inside the For loop in Python
For loops, in general, are used for sequential traversal. It falls under the category of definite iteration. Definite iterations mean the number of repetitions is specified explicitly in advance. But have you ever wondered, what happens, if you try to increment the value of the iterator from inside the for loop. Let's see with the help of the below
2 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++ Code i=0 while i<5: i+=1 print("i ="
3 min read
Python VLC Instance – Setting Loop on the media
In this article we will see how we can set loop on the single media from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can
2 min read
three90RightbarBannerImg