So far, our functions have printed output. But often you want functions to calculate something and give you the result to use elsewhere.
Copy
# This function only printsdef add_print(a, b): print(a + b)# This function returns a valuedef add_return(a, b): return a + b# Now you can use the resultresult = add_return(5, 3)print(f"The result is {result}") # The result is 8
def double(number): return number * 2# Store in variableresult = double(5)# Use in expressionstotal = double(5) + double(3) # 10 + 6 = 16# Pass to other functionsprint(double(10)) # 20# Use in conditionsif double(7) > 10: print("Big number!")
# Wrong - calculates but doesn't returndef calculate_total(items): total = sum(items) # Forgot return!# Rightdef calculate_total(items): total = sum(items) return total
Code after return
Copy
# Wrong - code after return never runsdef get_status(): return "Done" print("This never prints!") # Unreachable# Right - return lastdef get_status(): print("Checking status...") return "Done"
Printing instead of returning
Copy
# Wrong - prints instead of returningdef multiply(a, b): print(a * b)result = multiply(3, 4) # Prints 12total = result + 10 # Error! result is None# Right - return the valuedef multiply(a, b): return a * b