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

  1. def defines a function. Its body does not run yet.
  2. Python defines the function describe(). Its body does not run yet: it runs each time the function is called.
  3. Call area(2, 3): Python jumps into the function with width = 2 and height = 3.
  4. Inside the call: a new frame with its own local names, shown in Memory.
  5. return hands 6 back to the caller, and the frame disappears.
  6. Call area(2, 3): Python jumps into the function with width = 2 and height = 3.
  7. describe(4, 5) calls area itself: functions can call other functions.
  8. Inside describe, a call to area.
  9. result is created with the value 20.
  10. The function returns result.
  11. area() has finished, so its names are gone. The value it returned, 20, is stored in a.
  12. The function returns f"{width}x{height} has area {a}".
  13. describe(4, 5) calls area itself: functions can call other functions.
  14. print shows "hello" and returns None, since it has no return value.
  15. small = 6, text = "4x5 has area 20", nothing = None. Functions take inputs, return outputs, and each call gets its own frame.