A for loop in Python is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each item in the sequence. Here are some examples of using a for loop in Python:
- Iterating over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
- Iterating over a range:
for i in range(5):
print(i)
Output:
0
1
2
3
4
- Iterating over a string:
word = "hello"
for letter in word:
print(letter)
Output:
h
e
l
l
o
- Using the
enumerate
function to get the index and the item:
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(i, fruit)
Output:
0 apple
1 banana
2 cherry
- Using the
zip
function to iterate over multiple lists
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for x, y in zip(list1, list2):
print(x, y)
Output:
1 4
2 5
3 6
These are just some examples, and you can use for loops in many different ways depending on your needs.