Topic 32 of 58
Function Basics
Overview
Functions (def) are the primary building blocks of modular, reusable code in Python. They allow you to encapsulate logic, accept inputs (parameters), and return outputs. Python functions are incredibly flexible: they support default arguments, keyword arguments (allowing you to pass inputs out of order), and uniquely, they can effortlessly return multiple values at once without requiring complex data structures.
Syntax
python
# Basic function with a default parameter
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
# Using positional vs keyword arguments
print(greet("Alice")) # Uses default: "Hello, Alice!"
print(greet("Bob", greeting="Hi")) # Keyword overrides default
# Returning multiple values
def get_dimensions():
width = 1920
height = 1080
return width, height # Implicitly packs into a tuple
# Destructuring the returned tuple
w, h = get_dimensions()
print(f"Resolution: {w}x{h}")Common Pitfalls
- The Mutable Default Argument trap. Never use
def add_item(item, my_list=[]). The empty list is instantiated exactly ONCE when the function is defined. Successive calls will share and append to the same list. Always usemy_list=Noneinstead. - Placing non-default arguments AFTER default arguments (e.g.,
def func(a=1, b):). Python requires all mandatory parameters to be listed first.
Interview Questions
Q:
How does Python technically return multiple values from a function?
A:
Python implicitly bundles comma-separated return values into a single Tuple object. The caller can then seamlessly unpack that Tuple into separate variables.
Real-World Example
Correctly handling optional mutable arguments (the most common function bug in Python).
example
python
def append_to_log(message, log_list=None):
# Safely initialize the list ONCE PER CALL
if log_list is None:
log_list = []
log_list.append(message)
return log_list
# Works perfectly without persisting state across unconnected calls
log_a = append_to_log("System started")
log_b = append_to_log("User logged in")Check Your Knowledge
Test your understanding of Function Basics with these quick questions.