For loops in Python are used to iterate over a sequence (like lists, tuples, strings) or other iterable objects.
for item in sequence:
# Code to be executed for each item
# ...
The sequence
can be any iterable object. The loop iterates through each item in the sequence, assigning the current item to the variable item
in each iteration.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
message = "Hello, AIT!"
for char in message:
print(char)
Output:
H
e
l
l
o
,
A
I
T
!
coordinates = (10, 20)
for coord in coordinates:
print(coord)
Output:
10
20
for i in range(5): # range(5) generates numbers from 0 to 4
print(i)
Output:
0
1
2
3
4
colors = ["red", "green", "blue"]
for i in range(len(colors)):
print(f"Color at index {i}: {colors[i]}")
Output:
Color at index 0: red
Color at index 1: green
Color at index 2: blue
numbers = [10, 20, 30]
for index, number in enumerate(numbers):
print(f"Index: {index}, Number: {number}")
Output:
Index: 0, Number: 10
Index: 1, Number: 20
Index: 2, Number: 30
student = {"name": "Muntajeeb", "age": 20, "grade": "A"}
for key, value in student.items():
print(f"{key}: {value}")
Output:
name: Muntajeeb
age: 20
grade: A
For loops are very versatile and can be used to iterate over various types of sequences or iterables in Python. Always ensure you're working with something that's iterable. Using `range()` is essential when you need to iterate a specific number of times, or if you need the index of the item in the iteration.