Python For Loop

Post Reply
admin
Site Admin
Posts: 119
Joined: Fri May 10, 2024 2:46 pm
Location:

Python For Loop

Post by admin »

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.

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)

🧰 Advanced twist: for with enumerate()
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)
Post Reply