While Loop In Python
In Python, a while loop allows you to repeatedly execute a block of code as long as a certain condition remains true. This tutorial will guide you through the basics of while loops and provide examples of their use.
Syntax
while condition:
# Code to execute as long as the condition is true
The indented code block under the while statement is executed repeatedly while the condition remains true.
Example
# Example: Using a while loop to count from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1 # Increment count by 1 in each iteration
- Initialization: count = 1: We start by initializing a variable named count with the value 1.
- Condition: while count <= 5: This sets up a condition for the while loop to continue executing as long as the value of count is less than or equal to 5.
- Body: The indented code block beneath the while statement is the loop body.
- Incrementing: count += 1: This line increments the value of
count
by 1 in each iteration. It ensures that the loop progresses and eventually fulfills the exit condition.
Infinite Loop
Be cautious with while loops to avoid unintentional infinite loops. Always ensure the condition can become false. Below is an example of infinite loop
Example
# Example: Infinite loop
while True:
print("This is an infinite loop!")
If you run the above code your system will hang as it is a infinite loop which will never end as the condition in while will never become false.