Table of Contents
TogglePython’s while loop is a fundamental part of programming, allowing for repetitive execution of a block of code as long as a specified condition remains true. This guide explains how while loops work, various practical use cases, and how to avoid pitfalls such as infinite loops.
while condition:
# block of code to be executed
statement(s)
The while keyword begins the loop, followed by a condition. As long as the condition is true, the indented code block runs repeatedly.
count = 0
while count < 5:
count += 1
print("Iteration no. {}".format(count))
print("End of while loop")
In this example, the while loop will run until the count variable reaches 5. The loop prints the iteration number each time the block executes.
Output:
Iteration no. 1
Iteration no. 2
Iteration no. 3
Iteration no. 4
Iteration no. 5
End of while loop
var = '0'
while var.isnumeric():
var = input("Enter a number..")
if var.isnumeric():
print("Your input: {}".format(var))
print("End of while loop")
This example demonstrates a while loop that continues to ask for user input until the input is no longer numeric.
Output:
Enter a number.. 10
Your input: 10
Enter a number.. abc
End of while loop
A common issue in using while loops is creating an infinite loop—a loop that runs forever because the condition never becomes false. This is usually unintended, but in some cases, like server-client models, infinite loops can be useful.
var = 1
while var == 1:
num = int(input("Enter a number: "))
print("You entered:", num)
print("Goodbye!")
If you run the above code, it will continue to ask for a number indefinitely. You can terminate the loop using CTRL + C>.
Python allows the use of an else clause with a while loop. The code in the else block is executed when the loop terminates (i.e., when the condition becomes false).
count = 0
while count < 5:
count += 1
print("Iteration no. {}".format(count))
else:
print("While loop over. Now in else block")
print("End of while loop")
In this example, once the count reaches 5, the code in the else block will run.
Output:
Iteration no. 1
Iteration no. 2
Iteration no. 3
Iteration no. 4
Iteration no. 5
While loop over. Now in else block
End of while loop
The while loop is a powerful construct in Python that allows you to execute a block of code as long as a given condition holds true. Whether you're iterating through numbers, strings, or waiting for user input, mastering while loops is essential for any Python programmer.
