Python Loops Explained with Examples
Loops are one of the most important concepts in programming. They allow you to execute a block of code multiple times without rewriting it. In Python, loops are widely used for iteration, data processing, and automation tasks.
What is a Loop?
A loop is a control structure that repeats a block of code as long as a condition is true or for a specific number of iterations.
Types of Loops in Python
- for loop
- while loop
For Loop
The for loop is used to iterate over a sequence such as a list, tuple, string, or range.
# for loop example
for i in range(1, 6):
print(i)
Looping Through List
numbers = [10, 20, 30]
for num in numbers:
print(num)
While Loop
The while loop runs as long as the condition is true.
# while loop example
count = 1
while count <= 5:
print(count)
count += 1
Break Statement
The break statement is used to exit the loop immediately.
for i in range(1, 10):
if i == 5:
break
print(i)
Continue Statement
The continue statement skips the current iteration and moves to the next one.
for i in range(1, 6):
if i == 3:
continue
print(i)
Nested Loops
A loop inside another loop is called a nested loop.
# nested loop example
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Loop with Else
Python allows an else block with loops which executes when the loop finishes normally.
for i in range(3):
print(i)
else:
print("Loop completed")
Real-World Applications
- Processing large datasets
- Automation scripts
- Game development
- Data analysis
- Web scraping
Common Mistakes to Avoid
- Infinite loops in while
- Incorrect loop conditions
- Improper indentation
- Misusing break and continue
- Not updating loop variables
Advanced Concepts
- List comprehension
- Generator expressions
- Iterators and iterables
- Loop optimization
- Parallel loops
Practice Exercises
- Print numbers 1 to 100
- Find sum of numbers using loop
- Print multiplication table
- Reverse a list using loop
- Count vowels in string
Conclusion
Loops are essential for writing efficient and scalable programs. By mastering for loops and while loops, you can automate repetitive tasks and build powerful applications.