Master Python Functions: Syntax, Parameters, Defaults, and Advanced Tricks
This guide explains how to define Python functions, the role of return statements, differences between positional and keyword arguments, default‑parameter pitfalls, *args/**kwargs usage, argument unpacking, reference passing semantics, positional‑only/keyword‑only parameters, and anonymous lambda functions, all with clear code examples.
1. Defining a Function
Use the def keyword followed by the function name, optional docstring, body, and an optional return value.
def function_name(parameters):
"""optional docstring"""
# function body
return value # optionalExample:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")2. The return Statement
returnsends a result back to the caller. If omitted, the function returns None.
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
def say_hello():
print("Hello")
res = say_hello()
print(res) # None3. Positional vs. Keyword Arguments
Positional arguments are passed by order; keyword arguments are passed by name, allowing any order.
def person_info(name, age):
print(f"{name} is {age} years old.")
person_info("Bob", 25) # positional
person_info(age=30, name="Alice") # keyword4. Default Parameters and the Mutable‑Default Pitfall
Default values are evaluated once at function definition. Using a mutable object (e.g., []) can cause unexpected sharing between calls.
# Bad example
def bad_func(lst=[]):
lst.append(1)
return lst
# Good example
def good_func(lst=None):
if lst is None:
lst = []
lst.append(1)
return lst5. *args and **kwargs
*argscollects arbitrary positional arguments into a tuple; **kwargs collects arbitrary keyword arguments into a dictionary. Useful for generic decorators or forwarding arguments.
def demo(*args, **kwargs):
print("args:", args)
print("kwargs:", kwargs)
demo(1, 2, 3, name="Tom", age=25)
# args: (1, 2, 3)
# kwargs: {'name': 'Tom', 'age': 25}6. Unpacking Lists and Dictionaries
Use * to unpack a list into positional arguments and ** to unpack a dict into keyword arguments.
def func(a, b, c):
print(a, b, c)
lst = [1, 2, 3]
func(*lst) # 1 2 3
d = {"a": 10, "b": 20, "c": 30}
func(**d) # 10 20 307. Parameter Passing Semantics
Python uses object‑reference passing. Immutable objects (int, str, tuple) cannot be altered by the function, while mutable objects (list, dict) can be modified in‑place.
def modify_list(lst):
lst.append(4)
my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # [1, 2, 3, 4]
def modify_str(s):
s += " world"
msg = "hello"
modify_str(msg)
print(msg) # hello (unchanged)8. Positional‑Only and Keyword‑Only Parameters (Python 3.8+)
Parameters before / must be passed positionally; parameters after * must be passed by keyword.
def example(a, b, /, c, *, d):
print(a, b, c, d)
example(1, 2, 3, d=4) # correct
# example(a=1, b=2, c=3, d=4) # TypeError: a and b must be positional9. Lambda (Anonymous) Functions
Anonymous functions can be created with lambda. They are useful for short, throw‑away functions or functional constructs like map.
square = lambda x: x ** 2
print(square(5)) # 25
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x * x, numbers))
print(squared) # [1, 4, 9, 16]Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
