A for loop is used to repeat a block of code for each item in a sequence such as a list, tuple, string, or range of numbers.
A for loop executes a block of code once for every item in a sequence.
for variable in sequence:
statement
Here, the variable receives each item from the sequence one by one.
for i in range(5):
print(i)
The range(5) generates numbers from 0 to 4.
names = ["Rahul", "Amit", "Priya"]
for name in names:
print(name)
name = "Python"
for letter in name:
print(letter)
A string is a sequence of characters, so the for loop can process each character separately.
The range() function is frequently used with for loops.
for i in range(1, 6):
print(i)
for i in range(2, 7):
print(i)
The first value is included, but the second value is not included.
for i in range(1, 11, 2):
print(i)
The third argument specifies the step value.
for i in range(2, 11, 2):
print(i)
for i in range(1, 10, 2):
print(i)
numbers = (10, 20, 30, 40)
for number in numbers:
print(number)
numbers = {10, 20, 30}
for number in numbers:
print(number)
A for loop can iterate through the elements of a set. The order of set elements should not be relied upon.
student = {
"name": "Rahul",
"age": 20
}
for key in student:
print(key)
student = {
"name": "Rahul",
"age": 20
}
for value in student.values():
print(value)
student = {
"name": "Rahul",
"age": 20
}
for key, value in student.items():
print(key, value)
for i in range(1, 11):
if i % 2 == 0:
print(i)
total = 0
for i in range(1, 6):
total = total + i
print(total)
The loop adds the numbers from 1 to 5.
number = 5
for i in range(1, 11):
print(number * i)
Python also allows an else block with a for loop.
for i in range(5):
print(i)
else:
print("Loop completed")
A for loop can also be placed inside another for loop. This is called a nested for loop.
for i in range(1, 4):
for j in range(1, 3):
print(i, j)
numbers = input("Enter numbers: ")
for number in numbers:
print(number)
If the user enters:
The output will be:
students = ["Amit", "Rahul", "Priya", "Neha"]
for student in students:
print("Welcome", student)
names = ["Amit", "Rahul", "Priya"]
for i in range(len(names)):
print(names[i])
Here, len() returns the number of elements in the list.
The enumerate() function can be used when we need both the index and the value.
names = ["Amit", "Rahul", "Priya"]
for index, name in enumerate(names):
print(index, name)
for i in range(5, 0, -1):
print(i)
A negative step allows the loop to move backwards.
The statements inside a for loop must be indented.
for i in range(3):
print(i)
The print() statement belongs to the loop because it is indented.
for i in range(3):
print(i)
This can cause an indentation error.
Question: Which keyword is used to create a for loop in Python?