Usar el bucle for en Python


Example 1: Simple for Loop

# Example 1: Simple for loop
for i in range(5):
    print(f"Iteration {i}")
    

Example 2: Iterating Over a List

# Example 2: Iterating over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
    print(f"I like {fruit}")
    

Example 3: Using for with enumerate()

# Example 3: Using for with enumerate() to get index and value
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(f"Fruit {index + 1}: {fruit}")
    

Example 4: Nested for Loops

# Example 4: Nested for loops
colors = ['red', 'green', 'blue']
shapes = ['circle', 'square', 'triangle']

for color in colors:
    for shape in shapes:
        print(f"{color} {shape}")
    

Example 5: for Loop with else Block

# Example 5: for loop with an else block
numbers = [1, 2, 3, 4, 5]

for number in numbers:
    if number == 6:
        print("Found 6!")
        break
else:
    print("6 was not found in the list.")