Most of the time, Python listens to youāfor example, when you write code and it runs it. But did you know that Python also talks to you via stack traces? Letās take a closer look at these now.Ā
If you write something that the Python interpreter doesnāt understand (i.e., itās grammatically incorrect or impossibleālike importing a non-existent module), it will explode! š¤Æ
Iām joking, of course! Python will just stop or generate whatās known as an exception. We call this raising an exception. It occurs when an error interrupts a programās normal flow. Exceptions are raised in stack traces, which are messages that often start with the line Ā Traceback (most recent call last)Ā :

In this example, the stack trace shows a Ā NameErrorĀ , one of the native exceptions in Python.
The stack traces often contain everything you need to locate the error and debug your code. But sometimes, the information only tells you the bug type, not how it manifests in the code. Therefore, the exception location may not correspond to the cause but to where it becomes a problem for Python. As you remove bugs, the stack trace will show you the next ones.
Reading stack traces might seem daunting (especially ones with many lines). 𤯠Here are some handy tips to make it easier:
This part shows you the type of errorāitās often the same as the name of the exception. It also provides other information, such as the variable involved, and sometimes an explanation of how to resolve it.
This part shows the area of code containing the error. Thereās even an arrow to reveal the exact line (isnāt that helpful? š).Ā
This part can sometimes be very long, as it indicates code elements that refer to modules, classes, or functions used explicitly (i.e., used directly by you) or implicitly (used within a class or function youāre using) within the program.
The only part you should focus on here is your code, as you canāt change the code of modules you didnāt create. However, the better you get at reading a whole stack trace, the more youāll improve your programming skills.Ā
In the screencast below, Iāll show you what the most common exceptions in Python look like in the code. Youāll see an example of the following errors:
AttributeErrorĀ , Ā KeyErrorĀ ,Ā Ā IndexErrorĀ , Ā NameErrorĀ ,Ā and Ā SyntaxErrorĀ . š
To summarize, these are the errors you just saw:
AttributeErrorĀ : Each type of Python variable is a different type of object. You can access an attribute of an object by writing Ā object.attributeĀ and the method by writing Ā object.method()Ā . If you try to access a method or attribute that doesnāt belong to the object class, you get this error.Ā
KeyErrorĀ : This error occurs if you try to use a key that doesnāt exist in a dictionary object.
IndexErrorĀ : This means youāve searched for the position of an object that doesnāt exist, such as position 4 in a list that only has 3 positions.Ā
NameErrorĀ : This error occurs when you refer to a variable that doesnāt exist yet, or may not exist at all.
SyntaxErrorĀ : This error occurs when your Python code is grammatically incorrect.
Now letās examine Ā TypeErrorĀ ,Ā Ā ValueErrorĀ ,Ā Ā FileNotFoundErrorĀ , and Ā ModuleNotFoundErrorĀ :
Hereās a summary of the errors you saw in the screencast:
TypeErrorĀ : There are many possible causes, all to do with the type of variable used. For example, you might be trying to perform an unauthorized type of conversion.Ā
ValueErrorĀ : There are many possible causes, but it indicates a problem with values, even if the type is correct. For example, you might see this error if you try to convert a string containing something other than numeric digits into Ā intĀ .
FileNotFoundErrorĀ : The referenced file doesnāt exist, or the file path is broken.Ā
ModuleNotFoundErrorĀ : The referenced module is unknown. It needs to be installed on your system or created.
In the following chapters, youāll learn to debug these exceptions.
You can use the built-in Ā print()Ā function for debugging when thereās no error message.
Iām sure you agree that stack traces are very useful. However, sometimes your program might contain an error without raising an exception.Ā
What? An error without an error message? 𤨠I thought weād just covered all possible error types in Python!
Unfortunately, Python canāt read your mind, meaning that when you make a logic error that follows the languageās syntax, it canāt tell you. Look at the example below:
i = 0
while i < -10:
Ā Ā Ā print(i)
Ā Ā Ā i -=Ā 1The aim here is to print figures starting from -1 and ending with -10, but thereās an error, as it doesnāt output the intended result. š§
Itās now up to you to play the role of stack trace! But how? Using the Ā print()Ā function! For example, you can put a Ā print()Ā in front of the loop to check that the condition is respected:

The result of the condition is false, which explains why the program doesnāt enter the loop as it would if the condition were true. In this case, you must change the comparison to Ā iĀ > -10Ā . This gives you 0, which is greater than -10, so itās true.
At this stage, the program will work, but the numbers it returns go from 0 to -9 rather than -1 to -10. Letās add another Ā print()Ā to see how the variable Ā iĀ changes before and after modifying its value.Ā

When you look at the successive values of Ā iĀ , you can see that you must put the Ā print()Ā after the modification of the variable Ā iĀ to get values from -1 to -10. The program will then look like this:

As youāve just seen, the Ā print()Ā function can be a very effective debugger, allowing you to see how variables change throughout a program.
Thereās also another built-in Python function you can use for debuggingā Ā help()Ā . As its name suggests, this function enables you to obtain information on a language element, whether a class, an object, a function, or a variable. More specifically, it displays the content of the class or function docstrings.
Docstrings? What are they again?
Well, since you asked so nicely⦠š Docstrings are strings that occur at the beginning of a function or class definition. Theyāre written between triple quotes (single or double), as shown in the examples below. They describe a function or a class in varying levels of detail for future users. Almost all the functions you use contain docstrings. They are often content summaries of the official documentation of the element youāre using:

You can even pass functions such as Ā print()Ā ,Ā Ā type()Ā , and Ā help()Ā itself as parameters of the Ā help()Ā function, as shown below:


Itās time to put all of this into practice in the tkinter project in the GitHub repository. When you run the file main.py, youāll encounter some exceptions, which you can see below.
Try to find the source of these exceptions, and then watch the video to see what could have caused them.
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 297, in _get_default_root
Ā Ā Ā raise RuntimeError(f"Too early to {what}: no default root window")
RuntimeError: Too early to create image: no default root windowTraceback (most recent call last):
File "/main.py", line 81, in <module>
Ā Ā Ā text1 = Label(window, text="You", font=("Arial", "20", "bold"))
NameError: name 'Label' is not definedTraceback (most recent call last):
File "/main.py", line 106, in <module>
Ā Ā Ā zero = PhotoImage(file ='zero.jpg')
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 4064, in __init__
Ā Ā Ā Image.__init__(self, 'photo', name, cnf, master, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/__init__.py", line 4009, in __init__
Ā Ā Ā self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError: couldn't recognize data in image file "zero.jpg"Letās explore the exceptions raised by our rock-paper-scissors project in the following screencast. š¤
As you saw, we went through the exceptions raised by the program and explained their potential causes:
You must create the tkinter window before adding images with the Ā PhotoImageĀ function.
To be added, these images must be in the formats stipulated in the documentation.
The error linked to the Ā LabelĀ class is because it hasnāt been imported.Ā
You can see the code for the tkinter project in the GitHub repository.Ā
A stack trace is a message Python shows to give you information about a raised exception.
An exception is an error in a program that stops it from running, and in Python, several exceptions are native to the language.
You can use the Ā print()Ā function for debugging to monitor the behavior of variables in a program.
The Ā help()Ā function provides information about a class, an object, or a function. This information is described in docstrings.
Now that you've mastered stack traces, print, and the help function, you will learn how to use two modules for debugging! See you in the next chapter!