What is it?
A Python function is a named reusable block of code defined with def. Functions accept parameters and can return values. Python has powerful argument-handling with defaults, keyword arguments, and variable argument lists.
Why does it matter?
Functions are the primary unit of code reuse. Every Python program, library, and framework is built from functions. Understanding all argument types is necessary for reading professional Python code.
Learn Python functions — def, positional and keyword arguments, default values, *args, **kwargs, and variable scope.
Real-World Use Cases
- 📧 Email sending - send_email(to, subject, body, cc=None) — keyword arguments with defaults make the API flexible.
- 📊 Data processing pipeline - def clean(*dfs) accepts any number of DataFrames — *args enables flexible pipelines.
- ⚙️ Configuration builder - def configure(**settings) builds a config dict from keyword arguments.
- 🔄 Decorator functions - A function that accepts another function and adds behaviour around it.
def and Return Values
def greet(name):
return f"Hello, {name}!"
print(greet("Rahul")) # Hello, Rahul!
# Multiple return values (tuple)
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3,1,4,1,5,9])
print(low, high) # 1 9
Default and Keyword Arguments
def send_email(to, subject, body, cc=None, priority="normal"):
print(f"Sending to {to}: {subject}")
if cc: print(f"CC: {cc}")
send_email("r@ex.com", "Hello", "Hi there")
send_email(body="Hi", to="r@ex.com", subject="Hello", priority="high")
# AVOID mutable defaults!
def add_item(item, lst=None): # GOOD: use None sentinel
if lst is None: lst = []
lst.append(item)
return lst
*args and **kwargs
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3)) # 6
print(total(10, 20, 30)) # 60
def build_url(base, **params):
query = "&".join(f"{k}={v}" for k, v in params.items())
return f"{base}?{query}"
print(build_url("https://api.com/search", q="python", page=2))
# https://api.com/search?q=python&page=2
Q: What is the difference between *args and **kwargs?
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. Both names are conventions — only the * and ** matter. Use *args for variable numbers of similar inputs; use **kwargs for named optional configuration.
Comments (0)
No comments yet. Be the first!
Leave a Comment