TensorLearn
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?

  1. Local (Inside the function)
  2. Enclosing (Inside a parent function)
  3. Global (Top of the file)
  4. Built-in (Python defaults)
python
x = "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).
python
def 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")

Mark as Completed

TensorLearn - AI Engineering for Professionals