Here is a clear, complete, and exam-ready explanation of Loops in Python, perfect for BCA/MCA/B.Tech students.
Loops in Python
Loops are used to execute a block of code repeatedly until a condition is met.
Python provides two main types of loops:
- for loop
- while loop
Additionally, there are loop control statements:
breakcontinuepass
Let’s discuss all of these in detail.
1. for Loop in Python
A for loop is used to iterate over a sequence (list, string, tuple, dictionary, set) or any iterable object.
Syntax:
for variable in sequence:
statements
Example 1: Loop through a list
fruits = ["apple", "banana", "mango"]
for item in fruits:
print(item)
Output:
apple
banana
mango
Example 2: Loop through a string
for ch in "Python":
print(ch)
Example 3: Using range() function
range() generates a sequence of numbers.
for i in range(5):
print(i)
Output:
0 1 2 3 4
Example:
for i in range(1, 6):
print(i)
Output:
1 2 3 4 5
Example 4: Step value
for i in range(1, 10, 2):
print(i)
Output:
1 3 5 7 9
2. while Loop in Python
A while loop repeats a block of code as long as the condition is True.
Syntax:
while condition:
statements
Example 1: Basic while loop
i = 1
while i <= 5:
print(i)
i += 1
Output:
1 2 3 4 5
Example 2: Infinite loop
(Only for demonstration — avoid in real programs)
while True:
print("Running endlessly")
You can stop it by pressing Ctrl + C.
Example 3: Countdown
n = 5
while n > 0:
print(n)
n -= 1
3. Loop Control Statements
Python provides three keywords to control loops:
1. break
Stops the loop completely.
Example:
for i in range(10):
if i == 5:
break
print(i)
Output:
0 1 2 3 4
2. continue
Skips the current iteration and goes to the next one.
Example:
for i in range(6):
if i == 3:
continue
print(i)
Output:
0 1 2 4 5
3. pass
Does nothing — used as a placeholder.
Example:
for i in range(5):
if i == 2:
pass # No operation
print(i)
4. Nested Loops
A loop inside another loop.
Example: Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(i, "*", j, "=", i*j)
5. else Block with Loops
Python allows an else block after a loop.
The else part executes only if the loop completes normally (no break).
Example:
for i in range(5):
print(i)
else:
print("Loop finished")
Example with break:
for i in range(5):
if i == 3:
break
else:
print("This will not execute")
6. Practical Examples
Example 1: Sum of first 10 numbers
total = 0
for i in range(1, 11):
total += i
print(total)
Example 2: Reverse a number using while loop
num = 1234
rev = 0
while num > 0:
rev = rev*10 + num%10
num //= 10
print("Reversed:", rev)
Example 3: Print even numbers using for loop
for i in range(1, 21):
if i % 2 == 0:
print(i)
Summary
| Loop Type | Use |
|---|---|
for loop | Iterate through sequences |
while loop | Repeat until condition becomes false |
break | Exit loop |
continue | Skip iteration |
pass | Do nothing (placeholder) |
else with loop | Executes if loop ends normally |
