# Loops & reusable functions

Code With Purpose · Hinglish · Free starter lesson

## Concept

for loop list jaise iterable ka har item ek-ek karke leta hai. Indentation batata hai kaunsa code loop ke andar hai. range(3) se 0, 1, 2 milte hain; stop value include nahi hoti. if condition se decide karo kaunsi values process karni hain.

Function repeated kaam ko ek naam deta hai. Parameters inputs lete hain; return result caller ko wapas deta hai. print sirf screen par dikhata hai, return ka replacement nahi hai. Explicit return nahi ho toh function None return karta hai.

Function ko ek clear task do. Accumulator initial value se shuru hota hai aur loop mein update hota hai. Sab items ka result chahiye toh return loop ke baad rakho. Loop ke andar return karne se function jaldi khatam ho sakta hai. Empty list aur boundary values bhi socho.

## 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

count_even(values) banao jo even integers ki ginti return kare. [2, 3, 4, 0] aur empty list dono check karo.

## 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

Result return karo taaki agla code use dobara use kar sake.

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

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