How to Use Loops in Python with Real-World Examples
Loops in Python allow you to execute a block of code multiple times, making programming more efficient and reducing redundancy. They are useful for automating repetitive tasks, processing data structures, and implementing logic-driven workflows.
Types of Loops in Python
1. For Loop
A for
loop is used to iterate over a sequence such as a list, tuple, string, or range. It is helpful when the number of iterations is known .
Example1:
for i in range(5):
print(i)
Example2:
fruits=["apple","mango","banana"]
for fruit in fruits:
print(fruit)
Example3:
str="Rkdigital school"
for i in str:
print(i)
2. While Loop
A while
loop runs as long as the specified condition remains true. It is useful when the number of iterations is not predetermined.
Example1:
count=0
while count<5:
print(count)
count=count+1
Example2: calculate the sum of N numbers using while loop
n=10
sum=0
count=1
while count<=n:
sum=sum+count
count=count+1
print("sum of first 10 natural numbers",sum)
Advantages of Using Loops
- Automates repetitive tasks: Loops eliminate manual repetition by executing code multiple times.
- Efficient data handling: Useful for processing lists, tuples, dictionaries, and files.
- Improves readability: A well-structured loop makes code cleaner and easier to understand.
- Supports complex operations: Enables batch processing, simulations, and automated tasks.
Disadvantages of Using Loops
- Risk of infinite loops: If the exit condition is not properly defined, the loop may run indefinitely, causing performance issues.
- Can impact performance: Excessive looping can slow down execution, especially with large datasets.
- Complexity in nested loops: Deeply nested loops can be hard to manage and debug.
- Consumes memory: Unoptimized loops with large iterations may use excessive system resources.