Loops
In Python, loops are used to execute a block of code repeatedly. There are two main types of loops in Python:
- For Loop: Used to iterate over a sequence (such as a list, tuple, or string) or other iterable objects.
- While Loop: Used to execute a block of code as long as a given condition is
True.
1. For Loop
A for loop iterates over a sequence (such as a list, string, or range) and runs the block of code for each item in that sequence.
Syntax:
python
for item in iterable:
# Code to execute for each itemExample:
python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Output:
apple
banana
cherryYou can also use the range() function with a for loop to repeat a block of code a specific number of times.
Example:
python
for i in range(5):
print(i)Output:
0
1
2
3
42. While Loop
A while loop repeatedly executes a block of code as long as the given condition is True.
Syntax:
python
while condition:
# Code to execute as long as condition is TrueExample:
python
count = 0
while count < 5:
print(count)
count += 1Output:
0
1
2
3
4Common Loop Control Statements:
break: Exits the loop entirely.continue: Skips the current iteration and moves to the next one.else: A block of code that runs if the loop completes normally (not terminated bybreak).
Example with break and continue:
python
for i in range(10):
if i == 5:
break # Stop the loop when i is 5
if i % 2 == 0:
continue # Skip even numbers
print(i)Output:
1
3