Programming and Computation · Module 6 of 10
Functions and Modules
A formula you use twice should be a function. This module covers defining functions with parameters and a return value, calling them, giving parameters defaults, documenting them, and importing modules of ready-made functions.
Readiness check
This module makes code reusable. Tick only what you can do closed-notes.
- Recall the idea of a mathematical function, input to output.
- Recall stress equals force over area.
- Use variables, arithmetic, and returning a value.
- Recall converting Celsius to Fahrenheit.
- Recall that indentation defines a block.
The core idea
A function packages a calculation under a name. You def it with parameters, compute inside, and return a value; then you call it with arguments as often as you like. Default parameters, a docstring, and imported modules make functions convenient, documented, and reusable.
The moment you copy a formula a second time, you should have written a function instead. A function definition begins with def, a name, and a list of parameters in brackets, then an indented body that ends with return to hand a value back: def stress(F, A): return F / A. Once defined, you call it by name with arguments, stress(20000, 200e-6), and Python substitutes those values for the parameters and returns the result, which you can store or print. Functions turn a formula into a named, tested, reusable tool: fix a bug once and every call benefits. Parameters can have default values, def force(m, g=9.81), so common cases need fewer arguments while special cases can override them. A docstring, a short string just under the def, records what the function does, its inputs, and its output, so a reader (or you, later) knows how to use it without reading the body. Finally, you rarely write everything yourself: a module is a file of ready-made functions, and import math or import statistics brings a whole toolbox into your program. Functions and modules are how small scripts grow into reliable engineering tools.
def with clear parameters and a return.The skills, taught in order
Five skills make code reusable and readable.
6.1 Defining a function
def name(parameters): starts a function; the indented body ends with return value. The parameters are placeholders filled in when the function is called.
6.2 Calling with arguments
Call by name with arguments in order: stress(20000, 200e-6). The returned value can be stored, printed, or passed to another function.
6.3 Default parameters
Give a parameter a default with =: def force(m, g=9.81). Then force(2) uses 9.81, while force(2, 1.62) overrides it for, say, the Moon.
| Part | Example | Role |
|---|---|---|
| Definition | def stress(F, A): | names the function and parameters |
| Return | return F / A | hands a value back |
| Call | stress(20000, 200e-6) | runs it with arguments |
The three parts of using a function: define, return, call.
6.4 Docstrings
A short string just below the def documents the function: what it computes, its inputs and units, and what it returns. Good docstrings make a function usable without reading its body.
6.5 Modules
A module is a file of ready-made functions. import math gives you math.sqrt and math.pi; import statistics gives mean. Reusing tested library code beats rewriting it.
Engineering connection: a stress function, a unit converter, and a deflection formula become a small personal library you import into any analysis, tested once and trusted thereafter.
Worked example 1: a stress function
Write a reusable function for axial stress and use it for a 20 kN load on a 200 mm2 area.
def stress(F, A):
"""Axial stress = force / area. F in N, A in m2, returns Pa."""
return F / A
sigma = stress(20000, 200e-6)
print(f"{sigma/1e6:.1f} MPa")
Output:
100.0 MPa
- ProblemCompute axial stress for F = 20 kN, A = 200 mm2, with a reusable function.
- Given / findF = 20000 N, A = 200e-6 m2. Find the stress.
- Model
def stress(F, A): return F / A, then call it. - CodeThe docstring records the units; the call substitutes the arguments.
- Solvestress = 20000 / 200e-6 = 1e8 Pa = 100.0 MPa.
- Check20 kN over 200 mm2 is 100 N/mm2, which is 100 MPa, matching.
- ConclusionThe function now computes stress for any force and area, tested once.
Worked example 2: a temperature converter
Write a function that converts Celsius to Fahrenheit and use it for 100 and 37 degrees.
def c_to_f(c):
"""Convert Celsius to Fahrenheit."""
return c * 9 / 5 + 32
print(c_to_f(100))
print(c_to_f(37))
Output:
212.0
98.6
- ProblemConvert 100 and 37 degrees Celsius to Fahrenheit with one function.
- Given / findc = 100 and c = 37. Find the Fahrenheit values.
- ModelF = c times 9/5 plus 32, returned from the function.
- Solvec_to_f(100) = 212.0; c_to_f(37) = 98.6.
- CheckBoiling water is 212 F and body temperature is 98.6 F, both correct.
- ConclusionOne definition serves every conversion, and the docstring says what it does.
Misconceptions and diagnostics
| Mistake | Symptom | Diagnostic question | Correction |
|---|---|---|---|
| Printing instead of returning | Cannot reuse the result | "Do I need the value later?" | Use return; print at the call site if needed. |
| Forgetting return | The function gives None | "Did I return anything?" | End the function with return value. |
| Wrong argument order | Swapped inputs, wrong answer | "Which parameter is which?" | Match argument order to the definition, or name them. |
| Rewriting library code | Reinventing mean or sqrt | "Is this in a module already?" | Import math or statistics instead. |
Practice ladder
Write a function area(r) that returns the area of a circle, and call it for r = 5.
Show answer
def area(r): return math.pi * r ** 2; area(5) is 78.54.
Write force(m, g=9.81) and call it as force(2) and force(2, 1.62).
Show answer
def force(m, g=9.81): return m * g; force(2) is 19.62 N, force(2, 1.62) is 3.24 N (lunar gravity).
Write a documented function for beam tip deflection, delta = F L cubed over (3 E I), and call it with sample values.
Show answer
def deflection(F, L, E, I): return F * L ** 3 / (3 * E * I), with a docstring giving units. Call it and format the result in mm.
Build a small module of three engineering functions (for example stress, a unit conversion, and a safety factor) with docstrings, and use them together.
What good work looks like
Three def blocks each returning a value, each with a docstring naming inputs and units, called together in one calculation. A good answer reuses the functions instead of repeating formulas.
Working with AI, and proving it yourself
Use AI as a tutor, not a black box
Portfolio task
Turn three formulas you use often into documented functions and combine them in one short analysis script.
def with parameters, a return, a docstring with units, and a call that reuses it.Retrieval and spaced review
Closed notes. Answer out loud, then reveal.
1. What keyword defines a function?
def, followed by a name and parameters.
2. What does return do?
Hands a value back to the caller.
3. What is a default parameter?
A parameter with a preset value used when no argument is given.
4. What is a docstring for?
To document what a function does, its inputs, and its output.
5. What does import do?
Brings a module of ready-made functions into your program.
Textbook mapping
This module follows Hans Fangohr, Introduction to Python for Computational Science and Engineering. Use these references to read further.
| Topic in this module | Where to read more |
|---|---|
| Defining and using functions | Fangohr, Sections 7.2 and 7.3 |
| Default parameters and docstrings | Fangohr, Section 7.4 and Section 4.5 |
| Modules | Fangohr, Section 7.5, Modules |
Chapter numbers refer to Fangohr's Introduction to Python for Computational Science and Engineering. Any recent version is equivalent for study.