Module 18: Giving Back Results

Learn how functions return values using the `return` statement.

📦 Functions That Give Back

So far, our functions have performed actions, like printing. But often, we need a function to calculate something and give the result back to the part of the code that called it.

This is where the return statement comes in. It's fundamental for building useful, reusable code blocks, connecting to Abstraction (hiding details) and Decomposition (breaking down problems).

🎁 What Does `return` Do?

Think of it like a vending machine giving you an item.

📞

You Call the Function

You ask the function to do its job (like selecting an item).

➡️
⚙️

Function Works

It performs calculations or tasks (machine gets the item).

➡️
🎁

`return` Sends Back

The return keyword sends the calculated value back (you receive the item).

The return statement specifies the value a function call will produce.

⚙️ Why Are Return Values Crucial?

Returning values makes functions much more powerful and flexible.

🧩

Build Complex Logic

The output of one function can become the input for another. This allows decomposition – breaking big problems into smaller, manageable function calls.

🧱

Use Results Elsewhere

You can store the returned value in a variable and use it later in your program, promoting abstraction by using the result without needing to know *how* it was calculated.

🔧

Flexible Outputs

Functions can return various data types (numbers, strings, lists, booleans, etc.), making them adaptable to different needs.

Click cards to see why `return` is essential!

🎬 `return` in Action!

Let's see a simple function that adds two numbers and returns the sum.

def add_numbers(a, b):
# This function takes two numbers and returns their sum
return a + b
result = add_numbers(5, 3)

We define a function add_numbers that takes two parameters, a and b.

The keyword returnSends a value back from the function tells Python what value to send back when the function finishes. Here, it sends back the sum of a and b.

We call the function with 5 and 3. The function calculates 8.

The returned value (8) is then stored in the variable resultStores the value returned by the function. We could now print or use this `result` variable.

🧠 Quick Check!

Module 18 Theory Complete!

You've learned how functions give back results using `return`! This is key for building modular AI components.
Time to practice! Head to the Practice Zone or try the Advanced Practice.