while loop in Python

What is a while Loop? A while loop in Python is used to execute a block of code repeatedly as long as a specified condition remains True.

It is mainly used when we don’t know in advance how many times you want to execute the loop.

Syntax

while condition:
    # code block

Explanation:

Example: Basic while Loop.

Python

# Initialize variable
count = 1

# Run loop while condition is True
while count <= 5:
    print("Count is:", count)
    count = count + 1  # Increment to avoid infinite loop

Output: Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

Explanation

Infinite Loop Example If we forget to update the variable inside the loop, the loop never ends.

Python

# Warning: This will run forever!
x = 1
while x <= 5:
    print("x =", x)
    # missing x = x + 1

So, always ensure the condition will eventually become False.