Explanation of Python Loops: for and while (with Output)
1. For Loops in Python
A for loop is used to iterate over a sequence (like a list, tuple, dictionary, string, or range). It allows you
to execute a block of code multiple times, once for each item in the sequence.
Example 1: Iterating through a list
library = ['books', 'stories', 'kids']
for x in library:
print(x)
Output:
books
stories
kids
Example 2: Iterating through a string
name = "python"
for d in name:
print(d, end=' | ')
Output:
p | y | t | h | o | n |
Example 3: Using range()
for x in range(0, 30, 2):
print(x)
Output:
0
2
4
6
8
10
12
1
14
16
18
20
22
24
26
28
2. While Loops in Python
A while loop runs as long as a specified condition is True . It is often used when you do not know in
advance how many times you want the loop to execute.
Example 1:
x = 0
while x < 5:
print(x)
x += 1
Output:
0
1
2
3
4
Example 2: Iterating through a list
fruits = ['apple', 'orange', 'kiwi', 'grapes']
x = 0
while x < len(fruits):
print(fruits[x])
x += 1
Output:
apple
orange
kiwi
grapes
2
Example 3: Using break and continue
while True:
print("hello")
break
continue
Output:
hello
Summary
• Use for loops when you know the number of iterations.
• Use while loops when you want to repeat a block of code until a condition changes.