Loading lesson...
Functions as building blocks
Functions as building blocks
Topics covered: Keyword Arguments, Multiple Return Values, Nested Functions, Closures, Docstrings
When calling a function, you can specify arguments by name instead of relying on position. This makes code clearer, especially for functions with many parameters or when the meaning of arguments is not obvious. Keyword arguments also let you skip optional parameters and provide only the ones you need. Positional vs Keyword Args You have been using positional arguments exclusively until now, where the order of values determines which parameter receives which value. Keyword arguments let you expli
Functions often need to produce multiple related results. Python makes this natural by allowing functions to return multiple values at once. Python packages them into a tuple, which you can unpack into separate variables. This pattern is common throughout Python's standard library and professional codebases. Returning Multiple Values The return statement creates a tuple. You can unpack it immediately into separate variables (most common) or store the tuple for later access. Both approaches are v
You can define functions inside other functions. The inner function, called a nested function, is only accessible within the outer function. This keeps helper logic private and encapsulated, preventing pollution of the broader namespace. Basic Nested Function Define helper functions inside the main function when they are only meaningful in that context: Organizing Complex Logic Nested functions help organize complex functions into clear, named steps without creating module-level functions that a
A closure is a function that remembers variables from the scope where it was created, even after that scope has finished executing. This powerful pattern lets you create customized functions and maintain state between calls without using global variables or classes. Creating a Closure When a nested function references a variable from its enclosing function and is returned, Python creates a closure that captures that variable: How Closures Work When you call make_multiplier(2), Python creates a n
Basic Docstrings Use triple quotes for docstrings. A simple docstring is a single line that describes what the function does: Multi-line Docstrings For functions with parameters, return values, or complex behavior, use a multi-line docstring that documents the interface completely: This multiline docstring format provides everything a user needs: a summary, detailed description, parameter documentation, return value, exceptions, and usage examples. Docstring Structure A well-structured docstring