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.

01

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.
0 or 1 weak itemsContinue with this module.
2 weak itemsRevisit loops in Module 5.
3 or more weak itemsRevisit the calculator in Module 1.
02

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.

def stress(F, A): return F / Acall it: stress(20000, 200e-6)import math to reuse math functions

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.

The skill works when: a repeated formula becomes one def with clear parameters and a return.
The skill breaks down when: a function prints instead of returning, or forgets to return at all (giving None).
The concept. A function takes arguments, computes, and returns a value you can reuse for any inputs, the same idea as a mathematical function.
03

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.

PartExampleRole
Definitiondef stress(F, A):names the function and parameters
Returnreturn F / Ahands a value back
Callstress(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.

04

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
  1. ProblemCompute axial stress for F = 20 kN, A = 200 mm2, with a reusable function.
  2. Given / findF = 20000 N, A = 200e-6 m2. Find the stress.
  3. Modeldef stress(F, A): return F / A, then call it.
  4. CodeThe docstring records the units; the call substitutes the arguments.
  5. Solvestress = 20000 / 200e-6 = 1e8 Pa = 100.0 MPa.
  6. Check20 kN over 200 mm2 is 100 N/mm2, which is 100 MPa, matching.
  7. ConclusionThe function now computes stress for any force and area, tested once.
Result. 100.0 MPa.
05

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
  1. ProblemConvert 100 and 37 degrees Celsius to Fahrenheit with one function.
  2. Given / findc = 100 and c = 37. Find the Fahrenheit values.
  3. ModelF = c times 9/5 plus 32, returned from the function.
  4. Solvec_to_f(100) = 212.0; c_to_f(37) = 98.6.
  5. CheckBoiling water is 212 F and body temperature is 98.6 F, both correct.
  6. ConclusionOne definition serves every conversion, and the docstring says what it does.
Result. 212.0 and 98.6 degrees Fahrenheit.
06

Misconceptions and diagnostics

MistakeSymptomDiagnostic questionCorrection
Printing instead of returningCannot reuse the result"Do I need the value later?"Use return; print at the call site if needed.
Forgetting returnThe function gives None"Did I return anything?"End the function with return value.
Wrong argument orderSwapped inputs, wrong answer"Which parameter is which?"Match argument order to the definition, or name them.
Rewriting library codeReinventing mean or sqrt"Is this in a module already?"Import math or statistics instead.
07

Practice ladder

Level 1 · Direct skill

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.

Level 2 · Mixed concept

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).

Level 3 · Independent problem

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.

Transfer task | Real engineering

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.

08

Working with AI, and proving it yourself

Use AI as a tutor, not a black box

"Explain the difference between return and print in a function."
"Review my function's docstring for missing units."
"Write all my functions." Draft the def and return yourself.
"Why is my result None?" Check that you returned a value.

Portfolio task

Turn three formulas you use often into documented functions and combine them in one short analysis script.

Must include: a def with parameters, a return, a docstring with units, and a call that reuses it.
09

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.

TodayFinish this quiz and Levels 1 and 2 of the ladder.
+1 dayRe-write the stress function from memory.
+3 daysTurn two formulas into documented functions.
+7 daysMove on to data structures in Module 7.
+30 daysPackage repeated formulas as functions by reflex.
10

Textbook mapping

This module follows Hans Fangohr, Introduction to Python for Computational Science and Engineering. Use these references to read further.

Topic in this moduleWhere to read more
Defining and using functionsFangohr, Sections 7.2 and 7.3
Default parameters and docstringsFangohr, Section 7.4 and Section 4.5
ModulesFangohr, 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.