Python While Loop

What is a While Loop?

The while loop in Python runs a block of code as long as a specified condition remains true.

Basic Syntax

while condition:
    # Code block to execute

Try It Now

Example: Simple While Loop

x = 0
while x < 5:
    print(x)
    x += 1

Try It Now

Using a Break Statement

The break statement exits the loop when a condition is met.

x = 0
while x < 10:
    if x == 5:
        break
    print(x)
    x += 1

Try It Now

Using a Continue Statement

The continue statement skips the rest of the current iteration and proceeds to the next.

x = 0
while x < 5:
    x += 1
    if x == 3:
        continue
    print(x)

Try It Now

Else in While Loop

The else block runs when the loop condition becomes false.

x = 0
while x < 3:
    print(x)
    x += 1
else:
    print("Loop completed")

Try It Now

Infinite Loop

Be careful when writing while loops without a proper condition, as they can run indefinitely.

while True:
    print("This will run forever!")

Try It Now