Functions & Modules
Python - A Quick Start for existing Programers
3 min read
Published Sep 16 2025, updated Aug 17 2026
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:
def my_function(): print("My function")And then to call the function (needs to be under where it is defined):
my_function()Any function that doesn't return a value, will actually return a None value. To return a value you use the return keyword:
def my_function(): print("My function") return "My return value"Zero or many parameters can be passed to a function:
def my_function(my_parameter1, my_parameter2): print("My function", my_parameter1, my_parameter2) return "My return value"Optional parameters can be defined a default value, which means you can call them with a parameter or without and it takes the default:
def my_function(my_parameter1="Default value", my_parameter2=42): print("My function", my_parameter1, my_parameter2) return "My return value"result = my_function("Custom value", 100)result2 = my_function()When calling a function, you can specify the parameter names so that they can be added in any order:
def introduce(name, age): print(f"My name is {name}, and I am {age} years old.")introduce(age=25, name="Bob")Multiple positional arguments. Allows a variable amount of positional based parameters for a function, providing the parameters as a tuple:
def add_all(*args): return sum(args)print(add_all(1, 2)) print(add_all(1, 2, 3, 4, 5)) Multiple keyword arguments. Allows a variable amount of keyword based parameters for a fucntion, providing the parameters as a key value pair dictionary:
def show_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}")show_info(name="Alice", age=25, job="Engineer")Combining Normal Parameters, *args, and **kwargs:
def example(a, b, *args, c=10, **kwargs): print("a:", a) print("b:", b) print("args:", args) print("c:", c) print("kwargs:", kwargs)example(1, 2, 3, 4, 5, c=20, x=100, y=200)Results in:
a: 1b: 2args: (3, 4, 5)c: 20kwargs: {'x': 100, 'y': 200}Argument Unpacking with * and **:
def greet(name, age): print(f"Hi, I'm {name}, {age} years old.")# Using * to unpack a tupleperson = ("Alice", 30)greet(*person) # Hi, I'm Alice, 30 years old.# Using ** to unpack a dictperson_info = {"name": "Bob", "age": 25}greet(**person_info) # Hi, I'm Bob, 25 years old.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.
lambda arguments: expressionarguments→ 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:
# --- Basics ---add = lambda x, y: x + yprint("add(2, 3):", add(2, 3)) # 5# No argumentshello = lambda: "Hello!"print(hello()) # Hello!square = lambda x=2: x * xprint("square():", square()) # 4print("square(5):", square(5)) # 25nested = lambda x: (lambda y: y**x)print("nested power:", nested(2)(5)) # 25# --- filter() with lambda ---evens = list(filter(lambda n: n % 2 == 0, nums))print("filter -> evens:", evens) # [2, 4]# --- sorted() with lambda ---words = ["banana", "apple", "cherry"]sorted_by_length = sorted(words, key=lambda w: len(w))print("sorted by length:", sorted_by_length) # ['apple', 'banana', 'cherry']Function variable scopes
Local variables created in a function are only accessible in that function:
def my_func(): # local variable x = 10 print(x)my_func()print(x) # ERROR: x not definedGlobal 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:
# global variablex = 100def show(): # can read global variable but can't set print(x)show()Using the global keyword inside a function will use the global variable, rather than creating a new local variable:
x = 5def change(): global x x = 10change()print(x)# outputs 10 as the global variable is updated in the functionIn 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:
def outer(): x = "outer" def inner(): nonlocal x x = "inner" inner() print(x)outer()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:
def add(a, b): return a + bdef subtract(a, b): return a - bImporting a whole module, single import statement and then access the functions using name.function :
import my_utilsprint(my_utils.add(5, 3))print(ma_utils.subtract(5, 3))Importing specific functions or classes, as they are specifically named, you can call the function directly without the name. prefix:
from my_utils import addprint(add(5, 3))Importing more than one specific function or classes by comma separating the names:
from my_utils import add, subtractImporting with aliases, renaming the function or class when importing:
import my_utils as mufrom my_utils import add as additionprint(mu.subtract(10, 4))print(addition(7, 2)) Importing everything from a module in to the namespace, risky as can cause naming conflicts:
from my_utils import *print(add(1, 2))