4.9. DebuggingΒΆ
The traceback Python displays when an error occurs contains a lot of information, but it can be overwhelming. The most useful parts are usually:
What kind of error it was, and
Where it occurred.
Syntax errors are usually easy to find, but there are a few gotchas. Whitespace errors can be tricky because spaces and tabs are invisible and we are used to ignoring them.
>>> x = 5
>>> y = 6
File "<stdin>", line 1
y = 6
^
IndentationError: unexpected indent
In this example, the problem is that the second line is indented by one
space. But the error message points to y
, which is
misleading. In general, error messages indicate where the problem was
discovered, but the actual error might be earlier in the code, sometimes
on a previous line.
In general, error messages tell you where the problem was discovered, but that is often not where it was caused.
Try different values for weight in the above code and then answer the question below:
- x ** z
- Try again. ** is the exponent operator. With the values given, this evaluates to 1.
- y + 12
- Try again. With the values given, this evaluates to 24.
- x + y / z
- Dividing by z (0) will cause an error.
- z % 3
- Try again. With the values given, this evaluates to 0.
Q-3: Which of the following will cause an error if x = 2, y = 12, and z = 0?
- x >= 2 and y != 0 and (x/y) > 2
- Try again. This will evaluate to False because y = 0.
- x >= 2 and y != 0 and (x/y) > 2
- Try again. This will evaluate to False because y = 0.
- x >= 2 and (x/y) > 2 and y != 0
- Since y = 0, x/y will cause en erorr. The gaurd (y != 0) should be placed before that expression.
Q-4: Which of the following will cause an error if x = 6 and y = 0?