DEV Community

Techno-101
Techno-101

Posted on

While loop in Python

The while loop in Python is a fundamental control flow statement that is used to execute a block of code repeatedly as long as a given condition is true. It's an essential part of Python programming, especially when the number of iterations is not known before the loop starts. Here's a basic structure of the while loop:

while condition:
    # Block of code to execute
``
Here, condition is a boolean expression. If the condition evaluates to True, the code block within the loop is executed. After each iteration, the condition is evaluated again. The loop continues running as long as the condition remains true. When the condition evaluates to False, the loop stops, and the program continues with the next line of code after the loop block.

Key Features
Condition Checking: The condition is checked before the execution of the loop body. If the condition is false at the first iteration, the code block inside the while loop will not execute at all.
Indefinite Iterations: The while loop is particularly useful when the number of iterations is not predetermined and depends on some dynamic factors during runtime.
Example Usage
Simple Example
A simple example that uses a while loop to print numbers from 1 to 5.

Enter fullscreen mode Exit fullscreen mode

count = 1
while count <= 5:
print(count)
count += 1

Infinite Loop
An example of an infinite loop. Be careful with these, as they will continue forever unless interrupted.

Enter fullscreen mode Exit fullscreen mode

while True:
print("This will print forever. Press Ctrl+C to stop.")

Using else with while
You can also use an else block with a while loop. The else block is executed when the loop condition becomes False.

Enter fullscreen mode Exit fullscreen mode

count = 1
while count <= 5:
print(count)
count += 1
else:
print("Loop is finished, count is now greater than 5.")



Important Tips
Avoid Infinite Loops: Ensure that the condition for the while loop will eventually become false; otherwise, the loop will continue indefinitely.
Update the Condition Variable: Within the loop, make sure to modify one or more variables involved in the condition so that the loop can terminate.
Break and Continue: Use break to exit a loop prematurely and continue to skip the rest of the code inside the loop and proceed with the next iteration.
while loops are versatile and simple to understand, making them a great tool for handling scenarios where the exact number of iterations cannot be determined beforehand. Learn more with a [free python tutorial](https://www.almabetter.com/bytes/tutorials/python)!
Read more: [Control Statements in Python](https://www.almabetter.com/bytes/tutorials/python/basics-of-control-statements-in-python)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)