Chapter 7: Functions & Modules
Define reusable functions, document them with docstrings, handle flexible arguments, and organize code into modules & packages.
Downloadchapter7.py
Objectives
- Define and call functions with positional, keyword and default arguments.
- Write clear docstrings and inspect them via
help()
. - Understand local vs global scope; use
global
if needed. - Use
*args
and**kwargs
for variable arguments. - Create and import modules and packages; understand
__name__ == "__main__"
.
1. Defining Functions
Use def
keyword. Specify parameters and return
a value:
def greet(name):
"""Return a greeting string for the given name."""
return f"Hello, {name}!"
msg = greet("Alice")
print(msg) # Hello, Alice!
Parameters can have default values:
def power(base, exp=2):
return base ** exp
print(power(5)) # 25
print(power(2, 3)) # 8
2. Docstrings & Scope
Document functions with a triple-quoted string immediately below def
:
def add(a, b):
"""
Add two numbers.
Args:
a (int): first addend
b (int): second addend
Returns:
int: sum of a and b
"""
return a + b
help(add)
Variables inside functions are local by default:
x = 10
def foo():
x = 5 # local x
return x
print(foo(), x) # 5 10
Use global
to modify a module-level variable:
counter = 0
def inc():
global counter
counter += 1
3. *args & **kwargs
Accept arbitrary positional args:
def summarize(*args):
return sum(args)
print(summarize(1,2,3,4)) # 10
Accept arbitrary keyword args:
def config(**kwargs):
for key, val in kwargs.items():
print(f"{key} = {val}")
config(host="localhost", port=8080)
Combine both:
def mixed(a, *args, **kwargs):
print(a, args, kwargs)
mixed(1,2,3, x=10, y=20)
4. Modules & Packages
Every .py
file is a module. Import with:
# file: math_utils.py
def square(x):
return x*x
# in another file
import math_utils
print(math_utils.square(5))
Use from … import …
to bring names into scope:
from math_utils import square
print(square(6))
Group modules in a directory with an __init__.py
to form a package:
project/
└── utils/
├── __init__.py
└── math_utils.py
Protect script entry point:
if __name__ == "__main__":
# code to run when executed directly
pass
Exercises
- Write a function
multiply(a, b=1)
and test it with different args. - Create
stats.py
module withmean()
andmedian()
, then import and use them. - Implement a function accepting any number of positional and keyword args, and print them.
- Build a package
mypkg
with two modules and demonstrate importing from it.