Why organize your code?
As your scripts grow, they become harder to read and maintain. The solution? Split your code into functions and separate files. Benefits:- Reusable - Write once, use many times
- Readable - Main script stays simple and clear
- Testable - Easy to test individual functions
Creating helper functions
Let’s create simple helper functions for our sales analysis. In yoursales-analysis folder, create a new file called helpers.py:
The
:.2f in the format string rounds floating point numbers to 2 decimal places - perfect for displaying money!Using your functions
Now updateanalyzer.py to use these helpers:
How imports work
When you writefrom helpers import calculate_total:
- Python looks for
helpers.pyin the same folder - It runs that file and makes the functions available
- You can now use
calculate_total()directly
The file must be in the same folder for this simple import to work. We covered more complex imports in the Python paths section.
What you’ve accomplished
Look at what you’ve built! You started with a single Python file and now have:- An organized project structure
- Understanding of how Python finds files
- Code that reads real data and saves results
- Reusable functions in separate files
Learn error handling
Handle errors gracefully in your code