Loading...
Loading...
Send values back from functions with return
So far our functions have only printed output. But often you want a function to give back a value that you can store, use in calculations, or pass to another function. That's what return does.
def add(a, b):
result = a + b
return result
total = add(5, 3) # total = 8
print(total * 2) # 16 ā we can use the returned value!| Part | What it means |
|---|---|
| `return result` | Sends `result` back to where the function was called |
| `total = add(5, 3)` | `total` captures the returned value |
| Function ends | After `return`, the function stops immediately |
def square(x):
return x * x
print("This never runs!") # ā Dead code after return
result = square(4) # result = 16
print(result) # 16
print(square(5) + 10) # 35 ā call directly in an expressionStep by step for result = square(4):
def print_version(a, b):
print(a + b) # Shows 8 on screen, but returns NOTHING
def return_version(a, b):
return a + b # Returns 8, caller can use it
x = print_version(5, 3) # x = None (prints "8")
y = return_version(5, 3) # y = 8 (stores the value)
print(x + 5) # ā Error! Can't add None + 5
print(y + 5) # ā
13 ā y is the number 8def absolute_value(n):
if n < 0:
return -n
return n
print(absolute_value(-5)) # 5
print(absolute_value(3)) # 3| ā Wrong | Why | ā Right |
|---|---|---|
| `print(result)` instead of `return result` | Can't use the value later | `return result` |
| Putting code after `return` | Never runs ā unreachable code | Move it before `return` |
| Forgetting `return` ā function returns `None` | No explicit return = returns None | Add `return result` |
| `return a, b` expecting a single value | Returns a tuple `(a, b)`, not two separate values | Use a tuple or return separately |
Define a function calculate_area(length, width) that returns the area of a rectangle. Then call it with width=5 and height=8, store the result, and print it.
def calculate_area(length, width):
return length * width
area = calculate_area(5, 8)
print(f"Area: {area}")