Functions & Modules
Python - A Quick Start for existing Programers
3 min read
Published Sep 16 2025, updated Sep 30 2025
Guide Sections
Guide Comments
Functions
Functions are defined using the def keyword and then the contents of the function are indented. Function names, like variables, should be lower case snake case:
And then to call the function (needs to be under where it is defined):
Any function that doesn't return a value, will actually return a None value. To return a value you use the return keyword:
Zero or many parameters can be passed to a function:
Optional parameters can be defined a default value, which means you can call them with a parameter or without and it takes the default:
When calling a function, you can specify the parameter names so that they can be added in any order:
Multiple positional arguments. Allows a variable amount of positional based parameters for a function, providing the parameters as a tuple:
Multiple keyword arguments. Allows a variable amount of keyword based parameters for a fucntion, providing the parameters as a key value pair dictionary:
Combining Normal Parameters, *args, and **kwargs:
Results in:
Argument Unpacking with * and **:
Lambda functions
A lambda function is a small, anonymous function defined with the lambda keyword. They are useful for short, throwaway functions where using def would be overkill.
arguments→ zero or more parameters.expression→ a single expression (no statements, no multiple lines).- Returns the value of the expression automatically (no
returnneeded).
Limitations
- Can only contain one expression (no statements like
print,for,ifas standalone). - Not a replacement for normal functions — use
deffor anything non-trivial. - Less readable if overused (can hurt clarity).
Examples:
Function variable scopes
Local variables created in a function are only accessible in that function:
Global variables are accessible inside a function to read, however if you try and assign a variable a value, it will create a new local variable of that name:
Using the global keyword inside a function will use the global variable, rather than creating a new local variable:
In nested functions, variables in the outer function are enclosing scope. Use nonlocal to modify them rather than creating a new local variable in the inner function:
Modules
A module is a .py file that contains Python code (functions, classes, variables, etc.).
An example file with two functions, called my_utils.py:
Importing a whole module, single import statement and then access the functions using name.function :
Importing specific functions or classes, as they are specifically named, you can call the function directly without the name. prefix:
Importing more than one specific function or classes by comma separating the names:
Importing with aliases, renaming the function or class when importing:
Importing everything from a module in to the namespace, risky as can cause naming conflicts:














