Python For Loop
Posted: Wed May 29, 2024 1:00 pm
A for loop in Python is used to iterate over a sequence (like a list, tuple, string, range, etc.) and perform a block of code for each item in that sequence.
Example 2
Advanced twist: for with enumerate()
Sometimes you want both the index and the value:
Code: Select all
#For loop
for num in range(1, 6):
print("Example", num)Example 2
Code: Select all
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)Sometimes you want both the index and the value:
Code: Select all
colors = ['red', 'green', 'blue']
for index, color in enumerate(colors):
print(index, color)