Following up from my previous article on A Python Appetizer, I mentioned I'd look into errors later on and here it is…
Introduction
In this article, I will explain different types of errors that occur in a Python program as we can make certain mistakes while writing a program, which leads to errors when we try to run it.
The most common reason for an error in a Python program is when a certain statement is not in accordance with the prescribed usage, such an error is called a Syntax error. A Python program terminates as soon as it encounters an error, the interpreter immediately reports it, usually along with the reason. Different kinds of errors can occur in a program and it is useful to distinguish among them in order to track them down more quickly.
Syntax errors are produced when translating the source code and an incorrect statement is detected. They are usually easy to fix once you figure out what they are. Unfortunately, the error messages are often not so helpful. The most common message could be seen as;
SyntaxError: invalid syntax
, which is not very informative.
On the other hand, the message tells you where in the program Python noticed a problem. Sometimes the error is prior to the location of the error message, often on the preceding line. Most syntax errors could be as a result of typos, incorrect indentation, or incorrect arguments. Try looking out for some of these whenever you encounter such an error. For example, omitting the colon :
at the end of a def
statement that is, while defining a function.
A few ways to avoid common syntax errors include;
- Ensure a Python keyword is not being used for a variable name.
- Check that you have a colon at the end of the header of every compound statement, including
for
,while
,if
, anddef
statements. - Make sure that strings in the code have matching quotation marks.
- If you have multi-line strings with triple quotes (single or double), ensure to have terminated the string properly, as this may cause an invalid token error at the end of your program or the following part of the program would still be treated as a string.
- An unclosed opening operator
(, {, [
makes Python continue with the next line as part of the current statement. Generally, an error occurs almost immediately in the next line. - Check the indentation to make sure it lines up the way it is supposed to.
Now your program is syntactically correct, Python can compile it and start running but then something can also go wrong. 😖
This brings us to Runtime errors which occur when the interpreter is able to parse the program but while running, the program may exit unexpectedly. An instance could be when your program does nothing or it hangs which might possibly be as a result of an infinite loop or recursion. The first step in tackling such an error is to examine the place in the program where it occurred and see if you can figure out what happened.
Some of the most common Runtime errors include;
- Name Error: This is when you are trying to use a variable that does not exist in the current environment. Such as, referring to a local variable from outside the function where it is defined. Keep in mind that local variables are local and cannot be called or used outside the function or block where they are created.
- Type Error: There are a few possible causes;
- You are trying to use a value improperly, for example indexing a string, list, or tuple with something other than an integer.
- You are passing the wrong number of arguments to a function or method.
- Key Error: You are trying to access an element of a dictionary using a key that the dictionary does not contain.
- Index Error: The index you are using to access a list, string, or tuple is greater than its length. A print statement can be used to display the value of the index or the length of the array.
Another situation could be when the syntax of the source code may be valid but the algorithm being employed is not, this would lead to a Logical error sometimes referred to as semantic error. Logical errors are seen as the most difficult to fix because the interpreter provides no information about what is wrong. They occur when the program runs without crashing but produces an incorrect result, the error is caused by a twist in the program’s logic and no error message is seen because a syntax or runtime error has not occurred. Therefore, you will have to find the problem on your own by reviewing all the relevant parts of your code.
A few examples of Logical errors can be seen when;
- Using the wrong variable names
- Indenting a block to the wrong level
- Using integer division instead of floating-point division
- Using wrong Boolean expression and other numerical errors
The first step in solving such an error is to make a connection between the program and the behavior you are seeing, you should ask yourself these questions:
- Is there something the program was supposed to do which doesn’t seem to be happening? Find the section of the code that performs that function and make sure it executes when it is supposed to.
- Is a section of the code producing an unexpected effect? Make sure to understand the code in question, especially if it involves calling functions or methods in other Python modules. Try them out by writing simple test cases and checking the results.
Debugging Programs
Syntax errors are usually quite straightforward to debug, the error message shows the line in the program where the error is and that makes it easy to find and fix.
Runtime errors can be a little more difficult to debug as the error message and traceback can tell us where the error occurred but not necessarily what the problem is.
Logical errors, being the most difficult to fix can take quite some time while trying to debug because they don’t cause any errors that can be traced to a particular line in the code as seen in syntax and runtime errors.
It is important to test your code to make sure it works the way you expect. A quick and simple way of testing that a function is doing the right thing is to insert a print
statement after every line which outputs the results calculated on that line. Keep in mind not to do this excessively as it has its own disadvantage, such as cluttering your code. There are also some automated tools that can help in debugging errors and ensuring codes are kept as correct as possible to minimize the chances of new errors creeping in.
Some of these tools analyze our program’s syntax, report errors and bad programming style, while others let us analyze the program as it is running. Tools such as pdb, Pyflakes, Pylint, PyChecker, and pep8 analyze code for syntax errors as well as some kinds of runtime errors. They also print warnings about bad coding style, inefficient and potentially incorrect code. For example, variables and imported modules that were never used.
Hope this gives you a simplified understanding of Python errors and good luck finding that error! 😉
Resources
greenteapress.com/thinkpython/html/thinkpyt..