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
- Define the function:
def greet(name):. - Write the function body.
- 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
Noneas a default and initialize inside the function. - Variables assigned inside a function are local by default; use
globalornonlocalto modify outer scopes. - Forgetting
returncauses the function to returnNoneimplicitly.