Sub topic 3
Reading errors and running isolated Python programs
Assume you can open a terminal, run a Python script, and read basic Python code. This chapter focuses on diagnosing failures and preparing a project safely.
Reading a traceback
A traceback records where Python stopped and why. Read it from the bottom upward:
- Find the file name and line number.
- Read the final error type and message.
- Inspect that line and the code that produced its values.
print(mesage)This produces a NameError because Python cannot find a variable named mesage. The traceback points to the misspelled name. Fix the spelling, then run the script again.
Arguments and the main guard
A command-line argument is text supplied after the script name. The __main__ guard prevents a script from running automatically when another file imports it.
import sys
def greet(name):
return f"Hello, {name}!"
def main():
name = sys.argv[1] if len(sys.argv) > 1 else "world"
print(greet(name))
if __name__ == "__main__":
main()Run this file as follows:
python3 greet.py AdaPython stores Ada in sys.argv[1].
Virtual environments
A virtual environment gives one project its own interpreter settings and packages. This prevents one project’s dependencies from changing another project.
python3 -m venv .venv
source .venv/bin/activate
# Windows Command Prompt:
# .venv\Scripts\activate.batAfter activation, the terminal usually shows .venv in its prompt. Use deactivate when you finish.
Installing packages
Install packages into the active environment with the same interpreter that will run the project:
python -m pip install requests
python -m pip listUsing python -m pip avoids accidentally using pip from a different Python installation.
Troubleshooting setup problems
| Symptom | Check |
|---|---|
| Command not found | Try `python3` or Windows `py`; verify Python is on PATH |
| Wrong version | Run `python --version` and inspect the selected launcher |
| Package cannot be imported | Activate the environment and install with `python -m pip` |
| Permission error | Use a virtual environment instead of installing system-wide |
Exercise
A script works in one terminal but cannot import its package in another. What should you check first?
Show answer
Check whether the correct virtual environment is activated, then run python -m pip list and install the package there if needed.