7 stages2 sections22 units

01.05 Lesson 5 of 10

42 min

Functions & 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

Exercise

Split the project into modules

Move the project setup and summary logic into functions that can be imported independently.

  1. Create data_io.py with a function that reads a CSV path.
  2. Create audit.py with a function that reports row and column counts.
  3. Create main.py as the entry point.
  4. Return dictionaries or DataFrames from functions instead of printing inside them.
  5. Add a main guard to main.py.
Done when

Importing data_io or audit does not run the full report.

Free references

Study resources

3 links
  1. 01
    Defining functions Article

    Read function definitions, arguments, return statements and default values.

  2. 02
    Functions Video

    Watch the single 22-minute video for a worked function example.

  3. 03
    Modules Article

    Read how modules are imported and searched.

Check your understanding

Self-test

2 questions
  1. Question 1

    Why return a result instead of printing inside a reusable function?

  2. Question 2

    What does the __main__ guard protect?

Completion check

Move on when

Your project has reusable functions in separate modules and a small import-safe entry point.

Quick find

Search Michi

Type to search every stage, section, unit, topic and resource.

Enter opens the first result Esc closes

Reference

Keyboard shortcuts

n
Continue to the first unit not passed
j / k
Next / previous unit
1 2 3
Toggle learned, practised, passed
/
Open search
?
Show this help
Esc
Close open panels