In this tutorial, we will learn about the while loop in Python programming with the help of examples.
In programming, loops are used to repeat a block of code. For example, if we want to show a message 100 times, then we can use a loop. It’s just a simple example, we can achieve much more with loops.
In the previous tutorial, we learned about Python for loop. Here, we are going to learn about
Python while Loop
while loop is used to run a specific code until a certain condition is met.
The syntax of
while loop is:
while condition: # body of while loop
whileloop evaluates the
- If the
True, the code inside the
whileloop is executed.
conditionis evaluated again.
- This process continues until the condition is
False, the loop stops.
Flowchart for Python While Loop
Example: Python while Loop
# program to display numbers from 1 to 5 # initialize the variable i = 1 n = 5 # while loop from i = 1 to 5 while i <= n: print(i) i = i + 1
Output1 2 3 4 5
Here’s how the program works:
|The loop is terminated.|
Example 2: Python while Loops to Display Game Level
current_level = 0 final_level = 5 game_completed = True while current_level <= final_level: if game_completed: print('You have passed level', current_level) current_level += 1 print('Level Ends')
OutputYou have passed level 0 You have passed level 1 You have passed level 2 You have passed level 3 You have passed level 4 You have passed level 5 Level Ends
In the above example, we have used the
while loop to check the current level and display it on the console.
Infinite while Loop in Python
condition of a loop is always
True, the loop runs for infinite times (until the memory is full). For example,
# infinite while loop while True: # body of the loop
In the above example, the
condition is always
True. Hence, the loop body will run for infinite times.
Python While loop with else
while loop can have an optional
else block as well.
else part is executed after the
condition in the while loop evaluates to
False. For example,
counter = 0 while counter < 3: print('Inside loop') counter = counter + 1 else: print('Inside else')
OutputInside loop Inside loop Inside loop Inside else
Here, we have used the counter variable to print the
'Inside Loop' string three times.
On the fourth iteration, the condition in
False. Hence, the
else part is executed.
Note: The else block will not execute if the while loop is stopped by a break statement.
Python for vs while loops
for loop is usually used when the number of iterations is known. For example,
# this loop is iterated 4 times (0 to 3) for i in range(4): print(i)
And while loop is usually used when the number of iterations are unknown. For example,
while condition: # body of loop