While Loops in Python

A while loop allows you to execute a block of code repeatedly as long as a condition is true. The condition is checked before the code inside the loop is executed.

Basic While Loop:

Python
i = 1

while i <= 5:
    print(i)
    i += 1

# Output:
# 1
# 2
# 3
# 4
# 5

Using a Break Statement:

The break statement can be used to exit the loop prematurely if a condition is met:

Python
i = 1

while i <= 5:
    if i == 3:
        break
    print(i)
    i += 1

# Output:
# 1
# 2

Using a Continue Statement:

The continue statement skips the current iteration and moves on to the next iteration of the loop:

Python
i = 1

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

# Output:
# 2
# 4
# 5
# 6

While loops are useful when you need to repeat a block of code but don"t know in advance how many times it should be repeated.