Why this chapter matters
Well-scoped functions reduce bugs, and module boundaries make code easier to test, maintain, and reuse.
What you will learn
- Define functions with parameters and return values.
- Organize related logic into importable modules.
- Use __name__ == '__main__' to separate script execution from reusable code.
Lessons in this chapter
- Function signatures and returnsDesign small functions that perform one clear task.
- Scope and stateAvoid hidden dependencies by passing data explicitly.
- Module importsImport reusable functions without side effects.
- Guide: functions and modulesRefactor one long script into reusable files. Read the full guide →
Study task
Refactor a single-file report script into three functions and one helper module, then run it through one main entry function.
Chapter checkpoint
What does if __name__ == '__main__' protect against?
It prevents script-only code from running when the file is imported as a module in another file or test.