Loops in Python are used to execute a block of code repeatedly. Python provides two types of loops:
- for Loop – Used for iterating over sequences like lists, tuples, and strings.
- while Loop – Executes as long as a condition remains
True
.
1. The for
Loop
The for
loop is used to iterate over sequences (lists, tuples, dictionaries, strings, etc.).
Syntax:
for variable in sequence:
# Code to execute
Example 1: Looping through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example 2: Looping through a String
word = "Python"
for letter in word:
print(letter)
Output:
P
y
t
h
o
n
Using range()
in a for
Loop
The range()
function generates a sequence of numbers and is commonly used in loops.
Example 3: Looping with range()
for i in range(5):
print(i)
Output:
0
1
2
3
4
range(5)
generates numbers from0
to4
(excluding5
).
Example 4: Using range(start, stop, step)
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
range(1, 10, 2)
starts from1
, increments by2
, and stops before10
.
Looping through a Dictionary
student = {"name": "John", "age": 20, "grade": "A"}
for key, value in student.items():
print(key, ":", value)
Output:
name : John
age : 20
grade : A
Nested for
Loops
A for
loop inside another for
loop is called a nested loop.
for i in range(1, 4):
for j in range(1, 3):
print(f"i={i}, j={j}")
Output:
i=1, j=1
i=1, j=2
i=2, j=1
i=2, j=2
i=3, j=1
i=3, j=2
2. The while
Loop
A while
loop runs as long as a given condition is True
.
Syntax:
while condition:
# Code to execute
Example 1: Simple while
Loop
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
- The loop runs until
count
exceeds5
.
Using break
and continue
in Loops
1. break
Statement (Stops the loop immediately)
for num in range(1, 10):
if num == 5:
break
print(num)
Output:
1
2
3
4
- The loop stops when
num
reaches5
.
2. continue
Statement (Skips the current iteration and continues)
for num in range(1, 6):
if num == 3:
continue
print(num)
Output:
1
2
4
5
3
is skipped due tocontinue
.
Using else
with Loops
Python allows an else
clause with both for
and while
loops. The else
block executes when the loop finishes normally (without break
).
Example 1: else
with for
for num in range(1, 4):
print(num)
else:
print("Loop finished.")
Output:
1
2
3
Loop finished.
Example 2: else
with while
x = 1
while x < 4:
print(x)
x += 1
else:
print("While loop finished.")
Output:
1
2
3
While loop finished.
Nested while
Loops
i = 1
while i <= 2:
j = 1
while j <= 3:
print(f"i={i}, j={j}")
j += 1
i += 1
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3