Parameters & Return
Parameters let a function take values in, and return sends its result
back out to the caller. Read Defining Functions first.
Parameters and arguments
def greet(name): print("Hello,", name)greet("Ada")greet("Bo")This prints Hello, Ada then Hello, Bo. name is the parameter.
"Ada" and "Bo" are arguments: the values each call gives it.
Return a result
def subtract(first, second): return first - secondanswer = subtract(10, 3)print(answer)print(subtract(3, 10))This prints 7 then -7. Arguments match parameters in order, so
subtract(3, 10) sets first to 3. The caller can store the returned
value, print it or use it in a sum.
return is not print
print() shows a value on the screen. return hands a value back to the caller.
def show_double(number): print(number * 2)result = show_double(3)print(result)This prints 6, then None. show_double prints but returns nothing,
so result is None.
def double(number): return number * 2result = double(3)print(result + 1)This prints 7. The returned 6 can be used in more maths.
Note: return ends the function call straight away. Any lines after it
in that call do not run.
See also: Decomposition, Printing Output.
Your turn
Complete triple with one return statement.
12
def triple(number): # Return three times number. passanswer = triple(4)print(answer)Advanced reading
- Default values and keyword arguments — make a parameter optional and pass arguments by name.
- Local and global variables — why names made inside a function stay inside it.