What is a Function?
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. In Python, you define a function using the def keyword.
Defining and Calling Functions
Python uses indentation to define the body of a function. You can pass data, known as parameters, into a function, and it can return data as a result.
Function Parameters & Arguments
Python offers flexible ways to pass arguments. You can use positional arguments, keyword arguments, and even default values.
- Default Arguments: Assign a value in the definition if none is provided during the call.
- Keyword Arguments: Identify arguments by name so order doesn't matter.
- Arbitrary Arguments (*args): Pass a non-keyworded, variable-length argument list.
- **Keyworded Arbitrary Arguments (kwargs): Pass a keyworded, variable-length argument list.
Type Hinting (Modern Python)
Since you are familiar with Dart's static typing, you'll appreciate Python's type hinting. While not enforced by the interpreter, it makes code significantly more maintainable and helps IDEs catch bugs.
Lambda Functions (Anonymous)
Small anonymous functions can be created with the lambda keyword. They are restricted to a single expression.
Argument Types Comparison
| Type | Syntax | Use Case |
|---|---|---|
| Positional | def func(a, b) | Basic, ordered inputs |
| Default | def func(a=1) | Optional parameters |
| *args | def func(*args) | Passing a variable list of items |
| **kwargs | def func(**kwargs) | Passing variable named settings/configs |