Fixing errors

5.16. Fixing errors#

Every programmer makes errors, it’s normal. The most important step towards fixing errors is interpreting the error messages produced by Python. In Python, error messages come in the form of “exceptions” which produce a “traceback” [1] that declares the type of exception and which piece of code triggered it.

Here’s some broken code:

a = 42
k += a
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[1], line 2
      1 a = 42
----> 2 k += a

NameError: name 'k' is not defined

First, in the traceback, the last line indicates the type of the exception (NameError in this simple case) and the statement triggering it (k +=). The offending line is indicated by ---->.

Variables must be defined before they’re used

a = 42
k = 0
k += a

And a slightly more complicated case

def echo(name):

print(name

This is a SyntaxError – imbalanced (). Note the ^ in the traceback, which indicates the first place where the syntax is erroneous. It also indicates the line number. In the Jupyter case, these line numbers are within the cell. In a standard Python script, they are within the entire file.

Balance the parentheses.

def echo(name):
    print(name)

5.17. Exercises#

  1. Fix the errors in the following.

    name = "Tim"
    if name = "Tim":
        greet = "Fist bump!"
    else:
        greet = "Hi"
    
      Cell In[4], line 2
        if name = "Tim":
                ^
    SyntaxError: invalid syntax
    
  2. Consider the following function, which is meant to compute the square of a number, i.e. \(x^2\). Define the type of error and then fix it.

    def squared(num):
        return num * 2