Your function finally talks back
The problem...
Your functions calculate things. They print things. But the result stays inside the function — and disappears when the function ends.
You can't use it. You can't pass it to another function. You can't store it in a variable.
The function does the work — but keeps the answer to itself.
The idea!
return sends a value back to whoever called the function. The function computes — and hands the result back. You decide what to do with it.
The syntax
def function_name():
# do something
return value
The moment Python hits return — the function stops and sends the value back. Everything after return in the same function is ignored.
Your first return
def square(number):
return number * number
result = square(5)
print(result) # 25
The function computes 5 * 5 and sends 25 back. You store it in result and use it however you need.
Using the returned value
def square(number):
return number * number
print(square(3)) # 9 — use directly
x = square(4) # 16 — store it
print(x + square(2)) # 20 — combine
A returned value behaves like any other value. Print it. Store it. Use it in expressions.
return stops the function
def check(number):
if number > 0:
return "positive"
return "zero or negative"
print(check(5)) # positive
print(check(-3)) # zero or negative
The first return that executes — stops the function. The second one only runs if the first didn't.
Without return — None
def greet(name):
print(f"Hello, {name}.")
result = greet("Bull")
print(result) # None
A function without return returns None — Python's way of saying "nothing". It's not an error — it's just empty.
Heads up!
returnstops the function immediately — nothing after it runs- The returned value can be stored, printed, or used in expressions
- A function without
returnreturnsNone - You can have multiple
returnstatements — first one reached wins
The mindset shift
Stop thinking: "My function prints the answer."
Start thinking: "My function computes the answer and hands it back. I decide what to do with it."
What you should understand now
returnsends a value back to the caller- The returned value can be stored, printed, or passed to another function
returnstops the function — everything after it is ignored- Without
return— the function returnsNone