Section 1.6 Debugging
Error messages are an inevitable part of programming. When you make a syntax error and see a message, read it carefully for clues about the cause of the error. While some messages are helpful and descriptive, others may seem cryptic or confusing. With practice, you will develop valuable skills for debugging your code and resolving errors. Not all errors will produce an error message. Logical errors occur when the syntax is correct, but the program does not produce the expected output. Remember, mistakes are learning opportunities, and everyone makes them. Here are some tips for debugging your code:
- Read the error message carefully for information to help you identify and fix the problem.
- Study the documentation.
- Google the error message. Someone else has likely encountered the same issue.
- Search for previous posts on Sage forums.
- Take a break and return with a fresh perspective.
- If you are still stuck after trying these steps, ask the Sage community.
Let’s dive in and make some mistakes together!
Why didn’t this print
Hello, World!
on the screen? The error message informed us of a SyntaxError
. While the phrase invalid decimal literal
may seem confusing, the key issue here is the invalid variable name. Valid identifiers must start with a letter or underscore. They cannot begin with a number or use any special characters. Let’s correct the variable name by using a valid identifier.Here is another error:
In this case, we encounter a
NameError
because Hi
is not defined. Sage assumes that Hi
is a variable because there are no quotes. We can make Hi
a string by enclosing it in quotes.Alternatively, if we intended
Hi
to be a variable, we can assign a value to it before printing.Reading the documentation is essential to understanding how to use methods correctly. If we incorrectly use a method, we will likely get a
NameError
, AttributeError
, TypeError
, or ValueError
, depending on the mistake.Here is an example of a
NameError
:The
sort()
method must be called on the list object using dot notation.Here is an example of an
AttributeError
:Here is the correct way to use the
len()
method:Here is an example of a
TypeError
:The
append()
method only takes one argument. To add multiple elements to a list, use the extend()
method.Here is an example of a
ValueError
:Although the resulting error message is lengthy, the last line informs us that the argument must be a non-negative integer.
Finally, we will consider a logical error. If your task is to print the numbers from \(1\) to \(10\text{,}\) you may mistakenly write the following code:
The output will be the numbers from \(0\) to \(9\text{.}\) To include \(10\text{,}\) we need to adjust the range because the start is inclusive and the stop is exclusive.
For more information, read the CoCalc article about the top mathematical syntax errors in Sage
1
github.com/sagemathinc/cocalc/wiki/MathematicalSyntaxErrors