In the vast world of programming, Python stands out for its readability and simplicity, making it a favorite for beginners and experts alike. One of Python's most powerful constructs is the for loop, which allows for simple and elegant iteration over sequences. Today, we'll dive into the Python code examples for loops, exploring their application in various scenarios.

Before we jump into exemplifying Python's for loops, let's briefly recap what they are and their fundamental syntax. A for loop in Python iterates over a sequence (like list, tuple, string, or set), executing a block of code for each element in the sequence. The basic syntax looks like this:

Understanding the Basic For Loop
The following is a simple for loop example, using a list of fruits:

```python fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) ```
Output:
``` apple banana cherry ```
In this example, the loop iterates over each item in the 'fruits' list, assigning it to the 'fruit' variable, and then prints the fruit's name.

For Loop with Range Function
The Python `range()` function comes in handy when you need to create a sequence of numbers. It returns an immutable sequence of numbers within a specified range, starting from 0 by default, and increments by 1 (also by default). Let's see how we can use `range()` with a for loop.
```python for i in range(5): print(i) ```
Output:

``` 0 1 2 3 4 ```
Here, the `range(5)` function generates numbers from 0 to 4, and the loop iterates over these numbers, printing each one.
For Loop with Else
Did you know you can use an else statement with a for loop in Python? The `else` block will execute after the loop finishes, whether the loop was terminated by a `break` statement or not.

```python for i in range(10): if i == 5: break print(i) else: print("The loop finished naturally.") ```
Output:
``` 0 1 2 3 4 ```
The else statement won't be executed because the loop was terminated by a `break` statement.




















Nesting For Loops
You can nest for loops to iterate over multiple dimensions, similar to nested loops in other programming languages. Let's see how that works with a two-dimensional list (or matrix).
Iterating Over a Matrix
To iterate over a matrix (or a list of lists in Python), you need to nest two for loops. One for the outer list (rows) and one for the inner list (columns).
```python matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for row in matrix: for num in row: print(num, end=" ") ```
Output:
``` 1 2 3 4 5 6 7 8 9 ```
In this example, the outer loop iterates over each row in the matrix, and the inner loop iterates over each number in the current row, printing them out with a space as a separator.
Experimenting with for loops in Python can open up a world of possibilities. You can iterate over data, manipulate lists, or even create complex algorithms. There's no limit to what you can achieve with Python's for loops!