# Loops & reusable functions

Code With Purpose · English · Free starter lesson

## Concept

A for loop visits each item in an iterable such as a list. Python uses indentation to group the loop body. range(3) yields 0, 1, and 2; the stop value is excluded. An if statement lets you choose which values to process.

A function groups work under a name. Parameters receive inputs; return sends a result back to the caller. print displays a value but does not replace return. A function without an explicit return returns None.

Keep functions focused. An accumulator starts with an initial value and updates during iteration. Return after the loop when you need the result from all items; returning inside it often ends the function too early. Think about empty inputs and boundary values.

## Example

```python
def total_positive(values):
    total = 0
    for value in values:
        if value > 0:
            total += value
    return total

print(total_positive([4, -2, 6, 0]))
print(total_positive([]))
```

## Expected output

```text
10
0
```

## Exercise

Write count_even(values) that returns how many integers are even. Check [2, 3, 4, 0] and an empty list.

## Suggested solution

```
def count_even(values):
    count = 0
    for value in values:
        if value % 2 == 0:
            count += 1
    return count

print(count_even([2, 3, 4, 0]))  # 3
print(count_even([]))  # 0
```

## Takeaway

Return a result your next piece of code can reuse.

Reference: https://docs.python.org/3/tutorial/controlflow.html

https://codewithpurposeai.in/lesson-python-loops-functions.html?lang=english
