Contenidos
Example 1: Simple for
Loop
1 2 3 |
# Example 1: Simple `for` loop for i in range(5): print(f"Iteration {i}") |
Example 2: Iterating Over a List
1 2 3 4 |
# 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()
1 2 3 4 |
# 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
1 2 3 4 5 6 7 |
# 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
1 2 3 4 5 6 7 8 9 |
# 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.") |