Topic-3: Python Loops
Python has two primary types of loops, for loops and while loops, used to execute a block of
code multiple times. The choice depends on whether the number of iterations is known
beforehand or depends on a condition.
1)for Loop
A for loop is used for iterating over a sequence (such as a list, tuple, dictionary, set, or string).
Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Output
apple
banana
Cherry
Example using range():
for i in range(1, 6):
print(i)
Output:
1
5
2)while Loop
A while loop repeatedly executes a block of code as long as a given condition remains True
Example:
i = 1
while i <= 5:
print(i)
i += 1
Nested Loop (Loop inside another loop)
for i in range(1, 4):
for j in range(1, 3):
print(i, j)