Open In App

Python While Loop

Last Updated : 27 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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!


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
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: Exampl
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
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
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
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
Python | Avoiding quotes while printing strings
We often come across small issues that turn out to be big. While coding, the small tasks become sometimes tedious when not handled well. One of those tasks is output formatting in which we require to omit the quotes while printing any list elements using Python. Example Input : ['Geeks', 'For', 'Geeks'] Output : Geeks For GeeksAvoiding Quotes While
4 min read
three90RightbarBannerImg