Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
Call a Function Dynamically by Name in Python
Use globals() to look up and call a function by its name as a string, with optional arguments.
def greet():
return "Hello from greet!"
def add(a, b):
return a + b
def multiply(a, b):
return a * b
if __name__ == "__main__":
func_name = "add"
args = (3, 5)
# Call function dynamically by name from globals
result = globals()[func_name](*args)
print(f"{func_name}({', '.join(ma…
How to Use a Dispatch Table in Python (Map Strings to Functions)
Maps string command names to callable functions in a dictionary, then dispatches calls safely with error handling.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
raise ValueError("Division by zero")
return a / b
dispatch = {
"add": add,
"subtract": subtract,
"multiply": multiply,
"divide": divide,
}
def…
How to Use singledispatch for Type-Based Overloading in Python
This code demonstrates Python's functools.singledispatch decorator to create functions that behave differently based on the type of their first argument.
from functools import singledispatch
@singledispatch
def process(value):
return f"Unknown type: {type(value).__name__}"
@process.register(int)
def _(value):
return f"Integer: {value * 2}"
@process.register(str)
def _(value):
return f"String: {value.upper()}"
@process.register(list)
def _(value):
re…
Browse by section
Each section groups closely related Python snippets.
Functions & basics — Python code examples
What you will find here
This page collects functions & basics snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.