Name a block of code once, call it whenever you need it, pass values in and get a value back.
# define and call function
def greet():
print("Hello!")
greet()
# ans: Hello!
def only stores the function; its body runs when the function is called with ().
# function with one parameter
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice")
# ans: Hello, Alice!
The call creates a new frame on the stack, where the parameter name holds the argument "Alice".
call add witha and b.return sends the value back to where the call was made.
# multiple parameters
def add(a, b):
return a + b
result = add(5, 3)
# ans: result is 8
# return value
def square(x):
return x ** 2
result = square(5)
# ans: result is 25
# no return (returns None)
def print_message(msg):
print(msg)
result = print_message("Hi")
# ans: Hi (printed)
# ans: result is None
Printing shows a value on screen; it does not give the value back to the caller.
Predict the answer, then press → to trace the code and check.
# what is returned?
def func():
x = 5
func()
# ans: None (no return statement)
# what is result?
def add(a, b):
return a + b
result = add(10, 20)
# ans: 30
# function call without ()?
def greet():
return "Hello"
x = greet
# ans: x is the function object, not "Hello"
# what happens?
def multiply(x, y):
return x * y
multiply(5, 3)
# ans: 15 (but not stored)
# can you call before defining?
result = add(1, 2)
def add(a, b):
return a + b
# ans: NameError (function not defined yet)
# function with print vs return?
def func1():
print(5)
def func2():
return 5
x = func1()
y = func2()
# ans: 5 (printed)
# ans: x is None, y is 5
# nested function call?
def double(x):
return x * 2
result = double(double(5))
# ans: 20
# what is printed?
def test():
return 5
print("After return")
test()
# ans: 5 (return exits the function,
# ans: so the print never runs)
At the interactive prompt the returned 5 is echoed; nothing is printed by the function itself.
# function name case?
def MyFunction():
return 1
myfunction()
# ans: NameError (names are case-sensitive)
# redefining function?
def func():
return 1
def func():
return 2
func()
# ans: 2 (second definition overwrites first)
def stores the function under its name; name() runs it. Calling before the def line is a NameError.
Parameters are local names in that frame, filled from the arguments.
return ends the callIt hands one value back; code after it never runs. No return means None.
x = greet copies the function; x = greet() stores its result.