Python Material
TOPIC – 6 PYTHON FOR LOOPS
The For Loops in Python are a special type of loop statement that is used for sequential traversal. Python
For loop is used for iterating over an iterable like a String, Tuple, List, Set, or Dictionary.
In Python, there is no C style for loop, i.e., for (i=0; I <n; i++). The For Loops in Python is similar to each
loop in other languages, used for sequential traversals.
Table of Content
• How to use the for loop in Python
o Python For Loop with String
o Python for loop with Range
o Python for loop Enumerate
o Nested For Loops in Python
o Python For Loop Over List
o Python For Loop with Tuple
o Python For Loop with Zip()
• Control Statements that can be used with For Loop in Python
Flowchart of Python For Loop
For Loop flowchart
How to use the for loop in Python
In Python, the for loop is used to iterate over a sequence (such as a list, tuple, string, or dictionary) or any
iterable object. The basic syntax of the for loop is:
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Python For Loop Syntax
for var in iterable:
# statements
pass
Note: In Python, for loops only implement the collection-based iteration.
Here we will see Python for loop examples with different types of iterables:
Python For Loop with String
This code uses a for loop to iterate over a string and print each character on a new line. The loop assigns
each character to the variable i and continues until all characters in the string have been processed.
# Iterating over a String
print("String Iteration")
s = "Decent"
for i in s:
print(i)
Output:
String Iteration
D
e
c
e
n
t
Python for loop with Range
This code uses a Python for loop with index in conjunction with the range() function to generate a
sequence of numbers starting from 0, up to (but not including) 10, and with a step size of 2. For each
number in the sequence, the loop prints its value using the print() function. The output will show the
numbers 0, 2, 4, 6, and 8.
for i in range(0, 10, 2):
print(i)
Output :
0
2
4
6
8
2 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Python for loop Enumerate
In Python, the enumerate() function is used with the for loop to iterate over an iterable while also keeping
track of the index of each item.
l1 = ["eat", "sleep", "repeat"]
for count, ele in enumerate(l1):
print (count, ele)
Output
0 eat
1 sleep
2 repeat
Nested For Loops in Python
This code uses nested for loops to iterate over two ranges of numbers (1 to 3 inclusive) and prints the
value of i and j for each combination of the two loops. The inner loop is executed for each value of i in the
outer loop. The output of this code will print the numbers from 1 to 3 three times, as each value of i is
combined with each value of j.
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Output :
11
12
13
21
22
23
31
32
33
Python For Loop Over List
This code uses a for loop to iterate over a list of strings, printing each item in the list on a new line. The
loop assigns each item to the variable I and continues until all items in the list have been processed.
# Python program to illustrate
# Iterating over a list
l = ["decent", "for", "python"]
for i in l:
print(i)
3 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Output :
decent
for
python
Python for loop in One Line
Numbers =[x for x in range(11)]
print(Numbers)
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Python For Loop with Tuple
This code iterates over a tuple of tuples using a for loop with tuple unpacking. In each iteration, the values
from the inner tuple are assigned to variables a and b, respectively, and then printed to the console using
the print() function. The output will show each pair of values from the inner tuples.
t = ((1, 2), (3, 4), (5, 6))
for a, b in t:
print(a, b)
Output :
12
34
56
Python For Loop with Zip()
This code uses the zip() function to iterate over two lists (fruits and colors) in parallel. The for loop assigns
the corresponding elements of both lists to the variables fruit and color in each iteration. Inside the loop,
the print() function is used to display the message “is” between the fruit and color values. The output will
display each fruit from the list of fruits along with its corresponding color from the colours list.
fruits = ["apple", "banana", "cherry"]
colors = ["red", "yellow", "green"]
for fruit, color in zip(fruits, colors):
print(fruit, "is", color)
Output :
apple is red
banana is yellow
cherry is green
4 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
Control Statements with For Loop in Python
Loop control statements change execution from their normal sequence. When execution leaves a scope,
all automatic objects that were created in that scope are destroyed. Python supports the following control
statements.
Continue in Python For Loop
Python continue Statement returns the control to the beginning of the loop.
# Prints all letters except 'e' and 's'
for letter in 'decentclasses’:
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)
Output:
Current Letter : d
Current Letter : c
Current Letter : n
Current Letter : t
Current Letter : c
Current Letter : l
Current Letter : a
Break in Python For Loop
Python break statement brings control out of the loop.
for letter in 'decentclasses':
# break the loop as soon it sees 'e'
# or 's'
if letter == 'e' or letter == 's':
break
print('Current Letter :', letter)
Output:
Current Letter : e
For Loop in Python with Pass Statement
The pass statement to write empty loops. Pass is also used for empty control statements, functions, and
classes.
5 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
# An empty loop
for letter in 'decentforpython':
pass
print('Last Letter :', letter)
Output:
Last Letter : n
For Loops in Python with Else Statement
Python also allows us to use the else condition for loops. The else block just after for/while is executed
only when the loop is NOT terminated by a break statement.
# Python program to demonstrate
# for-else loop
for i in range(1, 4):
print(i)
else: # Executed because no break in for
print("No Break\n")
Output:
1
2
3
No Break
Python For Loop Exercise Questions
Below are two Exercise Questions on Python for-loops. We have covered continue statement and range()
function in these exercise questions.
Q1. Code to implement Continue statement in for-loop
clothes = ["shirt", "sock", "pants", "sock", "towel"]
paired_socks = []
for item in clothes:
if item == "sock":
continue
else:
6 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652
DECENT COMPUTER INSTITUTE PYTHON MATERIAL
print(f"Washing {item}")
paired_socks.append("socks")
print(f"Washing {paired_socks}")
Output
Washing shirt
Washing pants
Washing towel
Washing ['socks']
Q2. Code to implement range function in for-loop
for day in range(1, 8):
distance = 3 + (day - 1) * 0.5
print(f"Day {day}: Run {distance:.1f} miles")
Output
Day 1: Run 3.0 miles
Day 2: Run 3.5 miles
Day 3: Run 4.0 miles
Day 4: Run 4.5 miles
Day 5: Run 5.0 miles
Day 6: Run 5.5 miles
Day 7: Run 6.0 miles
DECENT COMPUTER INSTITUTE
7 | DECENT COMPUTER FF-12, AMBER COMPLEX, AJWA RD, BARODA-GUJARAT-INDIA M.+919825754652