Learning Sections show
While Loops in Python
The while
loop in Python is used to repeatedly execute a block of code as long as a condition is true. The loop will continue to run as long as the condition remains true.
Basic While Loop
The basic syntax of a while
loop in Python is:
# Basic while loop example
while condition:
# Code to execute
For example, a loop that prints numbers from 1 to 5:
# Printing numbers from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1
Using Break in While Loops
The break
statement can be used to exit the loop prematurely when a certain condition is met.
# Using break in a while loop
count = 1
while count <= 5:
if count == 3:
break
print(count)
count += 1
Using Continue in While Loops
The continue
statement can be used to skip the current iteration and proceed to the next iteration of the loop.
# Using continue in a while loop
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count)
Infinite Loops
If the condition in a while
loop never becomes false, the loop will continue to execute indefinitely. Be careful to avoid infinite loops, as they can cause your program to hang.
# Infinite loop example
while True:
print("This will run forever...")
Using Else with While Loops
An optional else
block can be used with a while
loop. The else
block is executed when the loop condition becomes false.
# Using else with while loops
count = 1
while count <= 5:
print(count)
count += 1
else:
print("Loop completed.")