In Python, the for
loop allows you to iterate over elements in a collection (such as a list, tuple, string, or dictionary) and perform operations on each item in the collection.
# Using a for loop to iterate over a list
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
# Using a for loop to iterate over a string
message = "Hello"
for char in message:
print(char)
# Using a for loop to iterate over a dictionary
student_grades = {"Alice": 85, "Bob": 92, "Charlie": 78}
for name, grade in student_grades.items():
print(f"{name}: {grade}")
# Using a for loop with the range() function
for i in range(5):
print(i)
# Using a for loop to calculate the sum of a list of numbers
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print("Sum:", total)
You can also nest `for` loops inside each other to perform more complex iterations and operations.
# Using nested for loops to create a multiplication table
for i in range(1, 6):
for j in range(1, 6):
result = i * j
print(f"{i} x {j} = {result}")
The `for` loop is a versatile tool for iterating over collections and performing actions on each element, making it a fundamental construct in Python programming.