Python Loops – for, while, and nested loops explained
IntroductionLoops are one of the most powerful features in programming.
They allow you to repeat a block of code multiple times, making your program shorter and more efficient.
Python supports two main types of loops:
-
for loop
-
while loop
1. The for Loop
A for loop is used to iterate over a sequence (like a list, tuple, string, or range).
Example:
for i in range(5):
print("Hello, Habbit2Code Online Coding Classes!")
Output:
Hello, Habbit2Code Online Coding Classes!
Hello, Habbit2Code Online Coding Classes!
Hello, Habbit2Code Online Coding Classes!
Hello, Habbit2Code Online Coding Classes!
Hello, Habbit2Code Online Coding Classes!
Example 2: Loop through a list
fruits = ["apple", "banana", "cherry"]
for item in fruits:
print(item)
Output:
apple
banana
cherry
2. The while Loop
The while loop runs as long as a condition is true.
Example:
count = 1
while count <= 5:
print("Count =", count)
count += 1
Output:
Count = 1
Count = 2
Count = 3
Count = 4
Count = 5
3. The break and continue Statements
-
break→ exits the loop completely. -
continue→ skips the current iteration and moves to the next one.
Example:
for i in range(1, 6):
if i == 3:
continue
if i == 5:
break
print(i)
Output:
1
2
4
4. Nested Loops
A loop inside another loop is called a nested loop.
Example:
for i in range(1, 4):
for j in range(1, 4):
print(f"({i}, {j})", end=" ")
print()
Output:
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)
5. Real-Life Example
Let’s print all even numbers between 1 and 20 using a loop.
for num in range(1, 21):
if num % 2 == 0:
print(num)
Output:
2, 4, 6, 8, ..., 20
Challenge for You
Write a program that prints a multiplication table for any number entered by the user using a for loop.
Final Thoughts
-
Use for when you know how many times to loop.
-
Use while when you don’t.
-
Add break and continue to control the flow inside loops.
Mastering loops is a huge step toward writing efficient, professional Python code.

Comments
Post a Comment