Python Lesson 10: Loops
PYTHON
AllComputerss
4/18/20261 min read


Loops are a fundamental concept in programming that allow you to execute a block of code repeatedly. In Python, loops help automate repetitive tasks, making your programs more efficient and easier to manage.
Types of Loops in Python
1. For Loop
The for loop is used to iterate over a sequence such as a list, tuple, string, or range.
# Example: Iterating through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple banana cherry
You can also use range() to generate a sequence of numbers:
for i in range(5):
print(i)
Output:
0 1 2 3 4
2. While Loop
The while loop executes as long as a condition remains true.
# Example: Counting with a while loop
count = 0
while count < 5:
print("Count is:", count)
count += 1
Output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Loop Control Statements
Python provides special keywords to control loop behavior:
break: Exits the loop entirely.
for i in range(5):
if i == 3:
break
print(i)
Output:
0
1
2
continue: Skips the current iteration and moves to the next.
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
else with loops: Executes a block of code after the loop finishes normally (without break).
for i in range(3):
print(i)
else:
print("Loop finished!")
Output:
0
1
2
Loop finished!
Nested Loops
You can place one loop inside another to handle complex iterations:
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
Output:
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
Conclusion
Loops are essential for handling repetitive tasks in Python. By mastering for and while loops, along with control statements like break and continue, you’ll be able to write programs that are more dynamic and efficient. In the next lesson, we’ll explore functions, which allow you to organize and reuse code effectively.
© 2026 AllComputerss. All rights reserved.