Back to Course
Python Essentials: The Engineering Approach
Module 5 of 20
5. Functions & Scope
The Call Stack
When a function runs, Python creates a "Stack Frame" in memory to hold its local variables. When the function ends, the frame is destroyed.
Scope (LEGB Rule)
How does Python look for variables?
- Local (Inside the function)
- Enclosing (Inside a parent function)
- Global (Top of the file)
- Built-in (Python defaults)
pythonx = "Global" def outer(): x = "Enclosing" def inner(): x = "Local" print(x) inner() outer() # Prints "Local"
*args and **kwargs
Engineers write flexible functions.
*args: Accepts any number of positional arguments (as a Tuple).**kwargs: Accepts any number of keyword arguments (as a Dict).
pythondef log(message, **data): print(f"[LOG] {message}") for key, value in data.items(): print(f" - {key}: {value}") log("User Login", id=123, ip="192.168.1.1")