Parameters, Return Values, and Scope
Return Values and Variable Scope
Return Values and Variable Scope
Until now, our functions have simply displayed a result with print. But often, you actually want the function to return a value, so it can be reused elsewhere in the program. That's the role of the return keyword:
def add(a, b):
return a + b
result = add(3, 5)
print(result) # (prints 8)
Unlike print, which simply displays a value on the screen without keeping it, return sends the value back to the place where the function was called, which lets you store it in a variable and keep using it (in a calculation, a comparison...).
Common mistake number 1: forgetting the return. A function without a return always returns the special value None, even if it displays something with print:
def add(a, b):
print(a + b) # (prints the result but does not return it)
result = add(3, 5)
print(result) # (prints None, not 8!)
Common mistake number 2: confusing print (displaying on screen, for a human) and return (returning a value, for the program). As soon as a return statement is executed, the function stops immediately: any code written after it is never executed.
You also need to know about variable scope: a variable created inside a function is local — it only exists while the function is running, and is inaccessible from outside. A variable created outside of any function is global — it is visible everywhere in the program (unless a local variable with the same name masks it locally).

