Functions & Scope
⚡ Topic 06 · Reusability
Functions & Scope
Write reusable, composable functions with parameters, return values, default arguments, and lambda expressions.
⏱ ~45 min
🟡 Intermediate
🏗️ Essential
Defining & Calling Functions
Use the def keyword. Functions run only when called, and can return values with return.
Default & Keyword Arguments
Parameters can have default values, and callers can pass arguments by name for clarity.
*args and **kwargs
Accept a variable number of positional (*args) or keyword (**kwargs) arguments.
Lambda Functions
Lambda creates small, anonymous one-expression functions — great for use as arguments to sorted(), map(), and filter().
Scope — the LEGB Rule
Python resolves variable names in this order: Local → Enclosing → Global → Built-in.
💡 global & nonlocal keywords
Use global x inside a function to modify a global variable. Use nonlocal x to modify a variable in the enclosing (non-global) scope.