A while loop in Python is a control flow statement that repeatedly executes a block of code as long as a specified condition remains True. It provides a way to create loops where the number of iterations is not known in advance and is determined by the condition. This makes while loops particularly useful for scenarios where the loop should continue until a certain condition is met.

Basic syntax of a while loop

The basic syntax of a while loop in Python is as follows:

while condition:
# Code to execute as long as the condition is True

condition: A Boolean expression that determines whether the loop should continue running (True) or stop (False).

Loop initialization

Before entering a while loop, you typically initialize one or more variables that are used within the loop. These variables are checked in the loop condition to decide whether the loop should continue or terminate.

# Step 1: Initialize a variable
count = 0

Quiz Question

Why is it important to initialize variables before entering a while loop in Python?

Loop condition

The condition specified after the while keyword is evaluated before each iteration. If the condition is True, the loop's block of code is executed; if the condition is False, the loop terminates, and program execution continues after the loop.

# Step 2: Set up the while loop with a condition
while count < 5:

Quiz Question

What is the output of the following code snippet?

num = 10
while num > 5:
num -= 2
print(num)

Quiz Question

True or False: The loop condition is evaluated after each iteration of the loop.

Loop body

The block of code indented under the while statement represents the loop body. This code is executed repeatedly as long as the condition remains True. You should include the logic that modifies the loop control variables within this block to eventually make the condition False and exit the loop.

# Step 3: Define the loop body
print(f"Count is {count}")
count += 1 # Increment count by 1 in each iteration

Infinite loops

If the condition specified in a while loop is never met or if there's no logic inside the loop body that can change the condition to False, you can create an infinite loop. Infinite loops can be problematic and should be avoided unless you have a specific use case for them.

Example of an Infinite Loop
while True:
print("This loop will run forever!")

To avoid infinite loops, ensure that the loop control variables are updated correctly within the loop body.

Loop control statements

Within a while loop, you can use control statements like break and continue to control the flow of the loop.

  • break: Terminates the loop prematurely, regardless of whether the condition is still True.

  • continue: Skips the current iteration and proceeds to the next iteration of the loop.

Example Using Break and Continue:
count = 0

while count < 10:
count += 1
if count == 5:
continue # Skip the iteration when count is 5
if count == 8:
break # Exit the loop when count is 8
print(f"Count is {count}")

print("Loop Finished")

Output:

Count is 1
Count is 2
Count is 3
Count is 4
Count is 6
Count is 7
Loop Finished

Quiz Question

What is the purpose of the break statement within a while loop?


Complete example of a while loop

Let’s put everything together in a complete example:

# Step 1: Initialize a variable
count = 0

# Step 2: Set up the while loop with a condition
while count < 5:

# Step 3: Define the loop body
print(f"Count is {count}")
count += 1 # Increment count by 1 in each iteration

# Step 4: End the while loop
print("Loop Finished")

Output:

Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Loop Finished

In this example, the while loop continues as long as the count variable is less than 5. It prints the value of count and increments it by 1 in each iteration until the condition count < 5 becomes False.

To recap…

While loops are a powerful tool in Python for executing a block of code repeatedly as long as a specified condition is true. They are particularly useful when the number of iterations is not known in advance. By understanding how to use while loops, including loop initialization, loop conditions, loop bodies, and control statements, you can write more efficient and flexible code. Always be cautious to avoid infinite loops by ensuring that the loop control variables are properly updated within the loop body.