How do I define and call functions in Python?

· Category: Python Programming

Short answer

Functions in Python are defined with the def keyword, followed by a name, parameters in parentheses, and an indented block. Use return to send a result back to the caller.

Steps

  1. Define the function: def greet(name):.
  2. Write the function body.
  3. Call the function: greet("Alice").
def greet(name, greeting="Hello"):
    """Return a personalized greeting."""
    return f"{greeting}, {name}!"

print(greet("Alice"))
print(greet("Bob", "Hi"))

Tips

  • Use default parameter values for optional arguments.
  • Document functions with docstrings.
  • Functions are first-class objects; they can be passed as arguments and returned from other functions.
  • Keep functions small and focused on a single responsibility.
# First-class function
def apply_twice(func, value):
    return func(func(value))

print(apply_twice(lambda x: x * 2, 3))  # 12

Common issues

  • Mutable default arguments are evaluated once at definition time, causing shared state across calls. Use None as a default and initialize inside the function.
  • Variables assigned inside a function are local by default; use global or nonlocal to modify outer scopes.
  • Forgetting return causes the function to return None implicitly.