Looping statements are used to execute a block of code repeatedly, either for a specific number of times or until a condition is met.
- A loop continues to execute as long as its condition remains true.
- Loops help in situations where repetitive tasks are required.
Types of Looping Statement in Python:
- for loop
- while loop
1.) for loop
The for loop is used when you know beforehand how many times you want to execute a statement or a block of statements.
Syntax:
for variable in sequence:
# Code to execute for each item
Example:
for i in range(1, 6):
print(f"Number: {i}")
2.) while loop
The while loop is used to execute a block of code as long as the specified condition is true. It checks the condition before executing the loop.
Syntax:
while condition:
# Code to execute
Example:
# Example: Count from 1 to 5
count = 1
while count < 5:
print(count)
count += 1
The else Clause after for or while Loops
In Python, for and while loops can have an optional else clause. The else block is executed after the loop completes naturally (i.e., without being terminated by a break statement).
Note: If the loop is interrupted with a break, the else block is skipped.
Syntax:
for item in iterable:
# Loop body
else:
# Code to execute after the loop ends naturally
while condition:
# Loop body
else:
# Code to execute after the loop ends naturally
→ Example with for Loop:
for i in range(5):
print(i)
else:
print("Loop completed naturally!")
Output:
0
1
2
3
4
Loop completed naturally!
→ Example with while Loop:
count = 1
while count < 3:
print(count)
count += 1
else:
print("While loop ended naturally!")
Output:
1
2
3
While loop ended naturally!
→ Example with break Statement:
for i in range(5):
if i == 3:
break
print(i)
else:
print("Loop completed naturally!")
Output:
0
1
2