Python Fundamentals ยท Functions
Functions: Define, Call, Return
Package code under a name, call it with arguments, and get a value back. Watch a new frame appear for each call.
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.