Python — Functions

A function is a named block of code that does one specific job. Define once, call anywhere. Functions make programs easier to write, read, test, and maintain.

Defining a Function

def greet_user():
    """Display a simple greeting."""    # docstring — triple quotes
    print("Hello!")
 
greet_user()    # call the function

Arguments

Positional (order matters)

def describe_pet(animal, name):
    print(f"I have a {animal} named {name}.")
 
describe_pet('hamster', 'harry')

Keyword (order doesn’t matter)

describe_pet(animal='hamster', name='harry')
describe_pet(name='willie', animal='dog')   # same result, different order

Default values

Parameters with defaults must come after parameters without defaults.

def describe_pet(name, animal='dog'):    # 'dog' is default
    print(f"I have a {animal} named {name}.")
 
describe_pet('harry', 'hamster')   # overrides default
describe_pet('willie')             # uses default 'dog'

Optional argument with None

def build_person(first, last, age=None):
    person = {'first': first, 'last': last}
    if age:
        person['age'] = age
    return person

Return Values

# Return a single value
def get_full_name(first, last):
    """Return a neatly formatted full name."""
    return f"{first} {last}".title()
 
musician = get_full_name('jimi', 'hendrix')
 
# Return a dictionary
def build_person(first, last):
    return {'first': first, 'last': last}

Passing Lists

A function receives a reference to the original list — any changes affect it directly.

def greet_users(names):
    for name in names:
        print(f"Hello, {name}!")
 
# Pass a copy with [:] to protect the original
greet_users(usernames[:])

Arbitrary Arguments

*args — collects extra positional args into a tuple

def make_pizza(size, *toppings):
    """Make a single-topping pizza."""
    print(f"Making a {size} pizza.")
    for topping in toppings:
        print(f"- {topping}")
 
make_pizza('large', 'bacon bits', 'pineapple', 'mushrooms')

**kwargs — collects extra keyword args into a dict

def build_profile(first, last, **user_info):
    user_info['first'] = first
    user_info['last']  = last
    return user_info
 
user_0 = build_profile('albert', 'einstein', location='princeton')

*args vs **kwargs

*args → extra positional arguments → tuple. **kwargs → extra keyword arguments → dict. Both can appear in the same function; *args must come first. The names args and kwargs are convention, not required.

Modules

A module is a .py file containing functions. Import it to reuse its functions in another file.

# Importing an entire module
import pizza
pizza.make_pizza('medium', 'pepperoni')
 
# Import a specific function (no module prefix needed)
from pizza import make_pizza
make_pizza('medium', 'pepperoni')
 
# Alias a module
import pizza as p
p.make_pizza('medium', 'pepperoni')
 
# Alias a function
from pizza import make_pizza as mp
mp('medium', 'pepperoni')
 
# Import everything — avoid (causes naming conflicts)
from pizza import *

Cross-References

  • PythonOOP — methods are functions where the first parameter is self
  • PythonLists — passing and slicing lists as function arguments
  • CppBuildProcess — Python modules parallel C++ header/library linking; import#include
graph TD
    A[Function] --> B["def name(params):"]
    A --> C[Positional args: order matters]
    A --> D[Keyword args: order doesn't matter]
    A --> E["Default values: param='default'"]
    A --> F["*args: extra positional → tuple"]
    A --> G["**kwargs: extra keyword → dict"]
    A --> H["return value"]
    A --> I[Module: separate .py file]
    I --> J["import / from import / alias"]