← Learning Hub
PythonFREE IN BOTH LANGUAGESLesson 02 / 12

Loops & reusable functions

Turn repeated work into a small function with a clear result.

Download notes (.md)

Downloads are text notes. Choose Save as PDF in your browser’s print dialog for a PDF copy.

Understand the 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.

Run the example

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([]))

Output / what to expect

10
0

Try it yourself

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

View a 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

Reference: Official documentation ↗

Make it yours.

Run the example and attempt the exercise before marking this lesson complete.

pass the idea on

What did this make you think?

You review and publish the post yourself. Instagram uses your device’s share menu when available; otherwise copy the text and link. Facebook opens the link composer, where you add your thoughts.