Python offers several types of loops to execute a block of code repeatedly:
The for Loop:
for variable in iterable:
# code to execute
A for loop iterates over a sequence of iterable objects in Python. The variable takes the value of each item in the iterable object, and the code inside the loop is executed for each value.
The while Loop:
while condition:
# code to execute
A while loop executes statements while the condition is True. The code inside the loop is executed repeatedly until the condition becomes False.
The else Statement with While Loop:
while condition:
# code to execute
else: # code to execute when the condition becomes False
A while loop with an else statement executes the code inside the loop while the condition is True. Once the condition becomes False, the code inside the else block is executed.
The do-while Loop:
while True: # code to execute at least once
if not condition: break
Python doesn't have a built-in do-while loop, but you can simulate it with a while loop and a break statement. The code inside the loop is executed at least once, and then the loop continues while the condition is True.
Example :
count = 0
while True:
print(f"Count: {count}")
count += 1
if count >= 5:
break
In this example, the loop will execute the code block at least once, printing the value of count
. After each iteration, the count
is incremented, and if it becomes greater than or equal to 5, the loop is terminated using break
.
The output of this code will be:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
The break Statement:
while condition:
# code to execute
if some_condition: break
The break statement terminates the loop it's in. This is useful when you want to skip over a part of the code or stop the loop based on some condition.
The continue Statement:
while condition:
# code to execute
if some_condition: continue
# code to execute after continue
The continue statement skips the rest of the loop statements and moves on to the next iteration. This is useful when you want to skip over certain elements in a loop.