The while
loop in Python repeatedly executes a block of code as long as a given condition is true. It is particularly useful when the number of iterations is not known beforehand and depends on some condition being met.
while condition:
# code block to be executed repeatedly
# Python program to demonstrate the use of a while loop
# Initialize a variable
counter = 1
# Use while loop to print numbers from 1 to 5
while counter <= 5:
print(f"Counter is: {counter}")
counter += 1
print("Loop is done!")
OUTPUT:
Counter is: 1
Counter is: 2
Counter is: 3
Counter is: 4
Counter is: 5
Loop is done!