Defining Functions in Python
Functions are the building blocks of reusable code. Use the
def keyword to define one. Significant indentation defines the body of the function.python
Function Arguments: Positional and Keyword
Python functions are incredibly flexible with how they receive data.
python
Arbitrary Arguments: *args and **kwargs
What if you don't know how many arguments will be passed?
1. *args (Non-keyword arguments as a tuple)
python
2. **kwargs (Keyword arguments as a dictionary)
python
Positional-Only and Keyword-Only Arguments (Python 3.8+)
Use
/ for positional-only and * for keyword-only.python
Type Hints (Python 3.5+)
While Python is dynamically typed, type hints make your intentions clear to other developers and IDEs. Note: Python does not enforce these at runtime.
python
Docstrings: Documenting Your Code
A triple-quoted string at the top of a function is its docstring. You can view it by typing
help(function_name).python
Scopes: Local vs Global
Variables created inside a function are local to it. To modify a global variable inside a function, use the
global keyword (though this is often discouraged).python
Summary
| Feature | Syntax | Purpose |
|---|---|---|
| Declaration | def name(): | Create function |
| Return | return val | Output from function |
| Default Arg | def f(x=10): | Optional parameter |
| Multiple Arg | *args | Arbitrary positional args |
| Named Arg | **kwargs | Arbitrary keyword args |
| Type Hint | def f(x: int): | Document input types |
| Docstring | """Docs here""" | Internal help/documentation |
| Best For | Reusable logic, abstraction |