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 Build Partial Functions with functools.partial in Python
Create reusable partial functions that pre-fill arguments using functools.partial, like making square and cube functions from a general power function.
```python
from functools import partial
def power(base, exponent):
"""Calculate base raised to the exponent power."""
return base ** exponent
# Create partial functions for common powers
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
if __name__ == "__main__":
squares = [square(x)…
How to Build a Simple Decorator That Logs Function Calls in Python
This code shows how to create a reusable decorator that logs each function call, including arguments, return value, and execution time.
import functools
import time
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} return…
How to Create Functions with Default Parameters in Python
This code defines two Python functions using default parameters to handle missing arguments gracefully, demonstrating how to work with optional inputs and keyword arguments.
def greet(name="Guest", greeting="Hello", punctuation="!"):
"""Generate a greeting message using default parameters."""
return f"{greeting}, {name}{punctuation}"
def create_profile(username="anonymous", age=0, city="Unknown", active=True):
"""Create a user profile dictionary with default values."""
r…
How to Define a Function with Default Parameter Values in Python
This code demonstrates defining a Python function with default parameter values, showing how to call it with zero, one, or two arguments.
def greet(name: str = "World", punctuation: str = "!") -> str:
"""Return a greeting message using default parameter values."""
message = f"Hello, {name}{punctuation}"
return message
if __name__ == "__main__":
# Call with no arguments – uses both defaults
print(greet())
# Call with one argume…
How to Document Python Functions with Google Style Docstrings
Document a Python function with a Google style docstring to describe arguments and return values clearly.
def calculate_rectangle_area(length: float, width: float) -> float:
"""Calculate the area of a rectangle.
Args:
length (float): The length of the rectangle in meters.
width (float): The width of the rectangle in meters.
Returns:
float: The area of the rectangle in square meters.
…
How to Invalidate Cache When Arguments Change in Python
A memoization decorator that caches function results keyed by arguments, automatically invalidating when inputs change.
from functools import wraps
def memoize(func):
cache = {}
@wraps(func)
def wrapper(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
@memoize
def expensiv…
How to Parse Command Line Arguments in Python with argparse
Build a CLI that accepts positional integers, an optional --sum flag, and a --verbose switch, all with Python's standard argparse library.
import argparse
def main():
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('numbers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
…
How to Parse Function Parameters with Defaults in Python
Create Python functions with default parameter values to make arguments optional and provide sensible fallbacks.
def greet(name, greeting="Hello", punctuation="!"):
"""Greet a person with customizable greeting and punctuation."""
return f"{greeting}, {name}{punctuation}"
def describe_fruit(fruit, color="unknown", ripe=False):
"""Describe a fruit with optional attributes."""
status = "ripe" if ripe else "not ripe…
How to Use *args and **kwargs in Python Functions
Implement a variadic function that accepts arbitrary positional and keyword arguments using *args and **kwargs.
def display_info(title, *args, **kwargs):
"""Display positional and keyword arguments received."""
print(f"Title: {title}")
print(f"Additional positional args ({len(args)}):")
for i, arg in enumerate(args, 1):
print(f" {i}. {arg}")
print(f"Keyword args ({len(kwargs)}):")
for key, value…
How to Use Default Parameter Values in Python Functions
Shows how to define and call Python functions with default parameter values, including overriding some or all defaults and using keyword arguments.
def greet(name, greeting="Hello", punctuation="!"):
"""Return a greeting message using default parameters."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
# Using defaults
print(greet("Alice"))
# Overriding first default
print(greet("Bob", "Hi"))
# Overrid…
How to Use Default Parameter Values in Python Functions
This code demonstrates how to define a Python function with default parameters and call it with varying numbers of arguments to see the defaults applied.
def greet(name, greeting="Hello", punctuation="!"):
message = f"{greeting}, {name}{punctuation}"
print(message)
if __name__ == "__main__":
greet("Alice")
greet("Bob", "Hi")
greet("Charlie", "Hey", "?")
How to Use Default Parameters in Python Functions
Define a Python function with default parameters and call it using positional and keyword arguments.
def greet(name, greeting="Hello", punctuation="!"):
"""Concatenate a greeting message with default parameters."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
print(greet("Alice")) # Uses both defaults
print(greet("Bob", "Hi")) # Uses default punctua…
How to Use Default Parameters with Python's Split Function
Create a reusable Python wrapper around str.split with sensible default parameters for delimiter and maxsplit, showing beginners how default arguments work.
def split_with_defaults(text, delimiter=" ", maxsplit=-1):
"""
Split a string into parts using a delimiter.
Default behavior: split on spaces, unlimited splits.
"""
parts = text.split(delimiter, maxsplit)
return parts
if __name__ == "__main__":
# Example usage with defaults and custom par…
How to Use Keyword-Only Arguments in Python Functions
Define Python functions with keyword-only arguments using the * separator to enforce clarity and prevent positional misuse.
def greet(name, *, greeting="Hello", punctuation="!"):
"""Greet someone with a customizable message using keyword-only arguments."""
message = f"{greeting}, {name}{punctuation}"
return message
if __name__ == "__main__":
# Basic call with only the positional argument
print(greet("Alice"))
# Al…
How to Use Lambda Sorting Keys in Python
Learn to sort lists of dictionaries using lambda functions as key arguments in Python's sorted() method.
# Demonstrate lambda as a sorting key function
students = [
{"name": "Alice", "grade": 88},
{"name": "Bob", "grade": 92},
{"name": "Charlie", "grade": 75},
{"name": "Diana", "grade": 95}
]
# Sort by grade (ascending) using a lambda key
sorted_by_grade = sorted(students, key=lambda student: student["g…
How to Validate Function Arguments in Python
Shows how to manually check argument types and values in a Python function, raising clear TypeError and ValueError messages.
def calculate_area(length: float, width: float) -> float:
"""Calculate the area of a rectangle with manual type validation."""
if not isinstance(length, (int, float)) or isinstance(length, bool):
raise TypeError(f"length must be a number, got {type(length).__name__}")
if not isinstance(width, (int,…
How to use function defaults in Python
Define Python functions with default parameter values so callers can omit arguments and use sensible fallbacks.
def greet(name="Guest", greeting="Hello", punctuation="!"):
"""Return a greeting message using default parameters."""
return f"{greeting}, {name}{punctuation}"
def describe_pet(pet_name, animal_type="dog"):
"""Display information about a pet with a default animal type."""
print(f"I have a {animal_type…
Python Function Default Parameters Explained with Examples
Learn how to define Python functions with default parameter values and call them with fewer arguments than declared.
def greet(name, greeting="Hello", punctuation="!"):
return f"{greeting}, {name}{punctuation}"
def calculate_area(length, width=1, unit="sq units"):
area = length * width
return f"Area: {area} {unit}"
if __name__ == "__main__":
print(greet("Alice"))
print(greet("Bob", "Hi"))
print(greet("Charl…
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.