Running Code and Reading Tracebacks
The REPL
The Python REPL is an interactive interpreter that you can use to quickly run code and experiments.
Newer versions of Python have introduced significant improvements, like syntax highlighting, and better paste.
The REPL is also useful for checking small expressions before you commit them to code:
uv run python
>>> "Release Tracker".lower().replace(" ", "-")
'release-tracker'
Info
If you ran this as a script, you'd need a wrap the output in a print() statement to see the result.
Running Code
Using VS Code
For one-off scrips, we can use the play button in VS Code to run our code.
We can also select parts of our code, and right click -> Run Python -> Run Selection/Line in Python terminal to run the lines in a Python REPL. This may not work if your VS Code is misconfigured.
VS Code doesn't use uv under the hood, but instead activates the underlying virtual environment.
Using UV
As our project grows, we'll run code three ways:
uv run python ...for quick scripts and one-off experimentsuv run pytestfor testsuv run devfor the API server
Example traceback
Let's add this to our main.py and run it:
"Release Tracker".lower().replaced(" ", "-")
and run it, Python raises an exception:
Traceback (most recent call last):
File "/Users/nina/projects/fem/learn-python/main.py", line 6, in <module>
main()
~~~~^^
File "/Users/nina/projects/fem/learn-python/main.py", line 2, in main
print("Release Tracker".lower().replaced(" ", "-"))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Read from the bottom up.
That tells us:
- strings have no method called
replacedand offers a helpful suggestion. - the error happened on line 2
- The function that caused the error was on line 6
Read The Traceback
When Python crashes, read the traceback from the bottom up:
- what exception happened?
- on which line?
- which function called that line?
Run early and often
Run and verify your code early and often to catch mistakes, and run tests to verify your work as you go.