Python Functions
Learn to define functions, use default arguments, *args, **kwargs, and return values.
Why Functions?
A function is a reusable named block of code you define once and call as many times as needed. Functions eliminate code duplication, make programs easier to read and test, and let you break a large problem into small, manageable pieces. The rule of thumb: if you write the same code more than twice, put it in a function.
Defining and Calling Functions
Use the def keyword, followed by the function name, parameters in parentheses, and a
colon. The indented body runs when called. return sends a value back. Without
return, the function returns None implicitly.
def greet(name): """Say hello — this is the docstring.""" print(f"Hello, {name}!") def add(a, b): """Return the sum of a and b.""" return a + b greet("Alice") greet("Bob") print(add(3, 7))
Hello, Alice! Hello, Bob! 10
Default Parameters
Parameters can have default values. If the caller omits that argument, the default is used. This makes functions flexible without requiring callers to specify everything every time. Defaults must come after required parameters.
def greet(name, greeting="Hello", punctuation="!"): print(f"{greeting}, {name}{punctuation}") greet("Alice") # uses both defaults greet("Bob", "Hi") # overrides greeting greet("Eve", greeting="Hey", punctuation=".")
Hello, Alice! Hi, Bob! Hey, Eve.
*args — Any Number of Arguments
Prefix a parameter with * to collect all extra positional arguments into a
tuple. Conventionally named args, but the star is what matters.
This lets you write functions that accept any number of inputs.
def total(*numbers): """Sum any quantity of numbers.""" print(f"Adding {len(numbers)} numbers: {numbers}") return sum(numbers) print(total(1, 2, 3)) print(total(10, 20, 30, 40))
Adding 3 numbers: (1, 2, 3) 6 Adding 4 numbers: (10, 20, 30, 40) 100
**kwargs — Keyword Arguments
Prefix with ** to collect extra named arguments into a dictionary.
Great for functions that accept optional named configuration — callers can pass any key-value pairs
they like.
def profile(**info): """Print whatever key-value info is passed.""" for key, val in info.items(): print(f" {key}: {val}") profile(name="Alice", age=28, city="London")
name: Alice age: 28 city: London
def — describing what the function does, its parameters, and what it returns.🧠 Quick Check
What keyword sends a value back from a function?