In Python (programming language), loops are used to repeat a block of code multiple times. They help automate repetitive tasks and make programs more efficient.
Python mainly provides two types of loops:
forloopwhileloop
πΉ 1οΈβ£ The for Loop
A for loop is used to iterate over a sequence such as a list, tuple, string, or range of numbers.
Syntax
for variable in sequence:
# code to execute
Example
for i in range(5):
print(i)
Output:
0
1
2
3
4
Here, the range(5) function generates numbers from 0 to 4.
Example: Loop Through a List
fruits = ["apple", "banana", "mango"]for fruit in fruits:
print(fruit)
Output:
apple
banana
mango
πΉ 2οΈβ£ The while Loop
A while loop runs as long as a condition is True.
Syntax
while condition:
# code to execute
Example
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
The loop continues until the condition i <= 5 becomes False.
πΉ Infinite Loop Example
If the condition never becomes False, the loop runs forever.
while True:
print("This will run forever")
β οΈ Infinite loops should be avoided unless intentionally used.
πΉ Using break in Loops
The break statement stops the loop immediately.
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
πΉ Using continue in Loops
The continue statement skips the current iteration.
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
β Key Points
- Loops allow repeating tasks automatically.
forloops are commonly used for iterating over sequences.whileloops run based on a condition.breakstops a loop early.continueskips the current iteration.