while Loop

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:

1while condition:
2   # block of code

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.

1i = 0
2while i < 5:
3    print(i)
4    i += 1

The output of this code will be:

0
1
2
3
4

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).

1i = 0
2while i < 5:
3    print(i)
4    i += 1
5else:
6    print('Loop has finished execution')

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.