Putting a folder on sys.path
Before the sys.path.append, the module in tools/ is invisible. After it, the import works. This is a quick fix in scripts and a poor design in real projects (Topic 6.8 shows the better way).
Any .py file is a module you can import. The line if __name__ == "__main__": lets one file work both as a program and as a library, and sys.path is the list of folders Python searches, which is why a file named after a standard module can break your program.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a file temperature.py with a function to_fahrenheit(c) that turns degrees Celsius into Fahrenheit. Add a main guard that prints to_fahrenheit(100) only when the file is run directly. Then, from your program, import it and call to_fahrenheit(37).
Write a program that prints I am the main program when it is run directly, and I was imported when another file imports it. Use __name__ and an if/else.
Make a folder libs containing a module greeting.py with one function hello() that returns "hello". Add the folder libs to sys.path, import greeting, and print greeting.hello().
Explain it without notes
What does if __name__ == "__main__": do, and why do people use it?
How does Python decide which file to load for import foo?
Why can naming your file random.py break a program, and how do you diagnose it?
What is the difference between python calc.py and python -m calc?
Expected output
ModuleNotFoundError: No module named 'notes'
found me in tools/
search path ends with: tools