Beginner level · Module 4: Writing Reusable Functions · Lesson 3 of 3
Breaking a Problem into Functions
Plan a program as a set of small functions, each with one clear job.
In this lesson you will
- Decompose a task into functions
- Build a main() function that coordinates the others
Key concepts
decompositionsingle responsibilitymain()if __name__ == '__main__'
The lesson
Large scripts become hard to read and fix. Decomposition means splitting a problem into small steps, each handled by one function with a clear name: load the data, clean each record, calculate results, print the report.
A main() function then reads like a summary of the program. The guard if __name__ == "__main__": main() runs main only when the file is executed directly — not when another file imports its functions, which you will do in the Intermediate level.
Refactoring means improving the structure without changing what the program does. Run the program before and after and compare the output; if it differs, the refactor introduced a bug.
Step by step
- Run the original script and save its output.
- Identify the separate jobs it does and name a function for each.
- Move code into the functions and call them from main().
- Run again and confirm the output is identical.
Practice activity
Refactor your Module 3 class register into functions: load_data, clean_record, print_register and main.
Expected result: The refactored program behaves exactly as before but is split into clear functions.
Check your understanding
-
What is the benefit of a main() function?
Show answer
It shows the program's overall steps in one place and keeps setup code out of the global scope.
-
Name one sign that a function is doing too much.
Show answer
It is long, has 'and' in its description, or mixes input, calculation and output.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.