Package code under a name, call it with arguments, and get a value back. Watch a new frame appear for each call.
Python · beginner · 8 min · 15 steps · free
What you'll learn
Define a function with def
Call it with arguments and use the return value
See that a function without return gives None
function_basics.py
def area(width, height):
result = width * height
return result
def describe(width, height):
a = area(width, height) # one function calling another
return f"{width}x{height} has area {a}"
small = area(2, 3)
text = describe(4, 5)
nothing = print("hello") # a function with no return gives None
print(small, text, nothing)
Step by step
def defines a function. Its body does not run yet.
Python defines the function describe(). Its body does not run yet: it runs each time the function is called.
Call area(2, 3): Python jumps into the function with width = 2 and height = 3.
Inside the call: a new frame with its own local names, shown in Memory.
return hands 6 back to the caller, and the frame disappears.
Call area(2, 3): Python jumps into the function with width = 2 and height = 3.
describe(4, 5) calls area itself: functions can call other functions.
Inside describe, a call to area.
result is created with the value 20.
The function returns result.
area() has finished, so its names are gone. The value it returned, 20, is stored in a.
The function returns f"{width}x{height} has area {a}".
describe(4, 5) calls area itself: functions can call other functions.
print shows "hello" and returns None, since it has no return value.
small = 6, text = "4x5 has area 20", nothing = None. Functions take inputs, return outputs, and each call gets its own frame.
Common mistakes
Printing a result inside a function and expecting to use it later: return it instead
Best practices
Make each function do one job, named with a verb
Key takeaways
def defines; calling runs the body.
Arguments fill the parameters in order.
return sends a value back; without it you get None.
Each call has its own local variables.
Check yourself
def f(): x = 5 — what does f() return?
Answer: None. There is no return statement.
When does a function body run?
Answer: When the function is called. def only stores it.