Here’s a basic example of using a for
loop in Python. In this example, the for
loop iterates over a sequence of numbers generated by the range()
function. It starts from 0 and goes up to, but does not include, 5. The loop body, which is indented, prints each number in the sequence.
# Iterating over a sequence of numbers
for i in range(5): # range(5) generates numbers from 0 to 4
print(i)
Iterating over elements in a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Iterating over characters in a string:
word = "Python"
for char in word:
print(char)
Iterating over a dictionary:
person = {"name": "Alice", "age": 30, "city": "New York"}
for key, value in person.items():
print(key, ":", value)