while Loop
On this page
The while loop is a basic loop structure in Python, which repeatedly executes a block of code as long as a given condition remains true. It’s one of Python’s ways to control the flow of execution in a program.
Syntax
The syntax for a while loop in Python is straightforward:
Here:
- The
while
keyword starts the loop. condition
is a logical expression that’s evaluated before each iteration. If it’s true, the loop continues. Otherwise, the loop ends.- The
# block of code
represents the actions performed during each iteration.
Example
Let’s see a basic example of a while loop.
The output of this code will be:
In this example, the program prints the value of i and increments it by 1 in each iteration, repeating these actions as long as i is less than 5.
Infinite Loops
Be cautious when working with while loops. If the condition never becomes false, the loop will continue indefinitely, resulting in an infinite loop that can potentially cause your program to crash.
Using ’else’ with a While Loop
In Python, you can use an else
clause along with the while
loop. The code block inside else
is executed once the while loop has finished (i.e., when the condition becomes false).
Now, once the loop completes its execution, the message ‘Loop has finished execution’ will be printed.
while loops are a powerful way to control the execution flow in your Python programs. With practice, you’ll be able to construct these loops quickly and instinctively, making your code both cleaner and more efficient.