🔄 Loops Statements
Last Updated: 14th August 2025
Loops let you repeat code without writing it again and again.
Hinglish Tip 🗣: Loop ka matlab — “jab tak kaam complete na ho, tab tak repeat.”
🛠 Types of Loops in Python
- for loop → iterate over a sequence (list, string, range, etc.)
- while loop → repeat as long as condition is
True
1. while Loop
A while loop runs as long as the condition is true.
Syntax:
while condition:
# repeat this block
Example:
i = 1
while i <= 5:
print(i)
i += 1
2. for Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
Hinglish Tip 🗣: For loop ka matlab — “sequence ke iteration.”
Syntax:
for item in sequence:
# repeat this block
Example:
# Iterate over a String:
text = "ABC"
for ch in text:
print(ch)
range function
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
Syntax:
range(stop) # 0 to stop-1
range(start, stop) # start to stop-1
range(start, stop, step) # start to stop-1 with step
Hinglish Tip 🗣: Range ka matlab — “number ke sequence.”
# Iterate with range():
for i in range(5):
print(i)
Nested Loops
Nested loops are loops inside loops.
Syntax:
# while
while condition:
# repeat this block
while condition:
# repeat this block
# for
for item1 in sequence1:
for item2 in sequence2:
# repeat this block
# combined
for item1 in sequence1:
while condition:
# repeat this block
Example:
# while
i = 0
while i < 5:
j = 0
while j < 5:
print(i, j)
j += 1
i += 1
# for
for i in range(5):
for j in range(5):
print(i, j)
# combined
for i in range(5):
j = 0
while j < 5:
print(i, j)
j += 1
else clause in loops
The else keyword in a loop specifies a block of code to be executed when the loop finishes without encountering a break statement.
(We’ll see interaction with break in the next lesson on Jump Statements.)
Hinglish Tip 🗣: else tab chalti hai jab loop normally finish ho jaye (i.e., beech me stop na ho).
Syntax:
# while
while condition:
# repeat this block
else:
# code to run if no break
# for
for item in sequence:
# repeat this block
else:
# code to run if no break
Example:
# while
k = 1
while k <= 3:
print(k)
k = k + 1
else:
print("Done")
# Output:
# 1
# 2
# 3
# Done
# for
for k in range(1, 4):
print(k)
else:
print("Done")
Hinglish Tip 🗣:Agar loop naturally khatam ho gaya, to else chalega.