Basic function definition:
Use
def keyword to define a function.
Function names should be lowercase (get_message).
The code inside the function must be indented.
The colon character (:) is required after the function signature.
Function parameters and arguments:
Parameters are variables in the function definition.
Arguments are actual values passed when calling the function.
Output:
Return values:
-
Single return value.
-
Multiple return values.
Positional arguments:
Output:
Keywords arguments:
Output:
Mixing positional and keywords arguments:
Positional arguments must be listed first.
Output:
Arbitrary positional arguments (*args):
Passing an arbitrary number of arguments.
Mixing regular arguments and *args:
Arbitrary keyword arguments (**kwargs)
Passing an arbitrary number of key-value pair as arguments.
Mixing regular arguments and **kwargs:
Passing regular and arbitrary number of key-value pair as arguments.
Combining all parameter types:
Default parameters:
Output:
Mutable defaults:
You need to avoid mutable defaults like lists or dictionaries.
To fix the issue, use None:
Passing lists as arguments:
Passing a copy of a list as an argument:
Working with lists copies:
Local and global variables
Lambda functions
-
Basic lambda:
-
Lambda with multiple arguments:
-
Lambda with map function:
-
Lambda with filter function:
-
Sorting with lambda:
Using functions as arguments
Return functions
Modules and imports
-
Creating a module:
Create a file function_module_1.py that contains the definition of two functions:
-
Import entire module:
Create a file function_import_1.py that imports the module function_module_1 (function_module_1.py):
-
Import specific functions:
Create a file function_import_2.py that imports specific functions defined in the module function_module_1 (function_module_1.py):
-
Import all:
Create a file function_import_3.py that imports all functions defined in the module function_module_1 (function_module_1.py):
-
Import with alias (as):
Create a file function_import_4.py that imports the module function_module_1 (function_module_1.py) and give it an alias f1:
-
Import specific functions with aliases (as):
Create a file function_import_5.py that imports specific functions defined in the module function_module_1 (function_module_1.py) and give them aliases: