01.05 Lesson 5 of 10
42 minFunctions & Modules
Turn repeated steps into small functions and split a project into importable files.
By the end of this lesson
You will be able to
- Define functions with clear inputs and outputs.
- Return results rather than relying on hidden state.
- Import code from another Python file.
- Use a main guard to separate imports from script execution.
A function should do one job
Give a function a clear name, explicit inputs and a useful return value. Prefer returning a result over printing from inside every function; the caller decides whether to print, save or test it.
def mean(values):
if not values:
raise ValueError("values cannot be empty")
return sum(values) / len(values)
result = mean([10, 20, 30])
print(result) Separate reusable code from script entry
Put reusable functions in a module and call them from a small entry-point file. The if __name__ == "__main__" guard prevents the script-only workflow from running when the module is imported elsewhere.
# summaries.py
def describe_count(values):
return {"total": sum(values), "rows": len(values)}
# main.py
from summaries import describe_count
if __name__ == "__main__":
print(describe_count([10, 20, 30])) Apply what you learned
ExerciseSplit the project into modules
Move the project setup and summary logic into functions that can be imported independently.
- Create
data_io.pywith a function that reads a CSV path. - Create
audit.pywith a function that reports row and column counts. - Create
main.pyas the entry point. - Return dictionaries or DataFrames from functions instead of printing inside them.
- Add a main guard to
main.py.
Importing data_io or audit does not run the full report.
Free references
Study resources
- 01 Defining functions Article
Read function definitions, arguments, return statements and default values.
- 02
- 03
Check your understanding
Self-test
-
Question 1
Why return a result instead of printing inside a reusable function?
The caller can test the result, combine it with other operations, or choose how to display it. -
Question 2
What does the
__main__guard protect?It runs the entry-point block only when that file is executed directly, not when imported as a module.
Completion check
Move on when
Your project has reusable functions in separate modules and a small import-safe entry point.