Chapter 14 Common Errors and Logical Flaws
Fixing code is a two-step process of first making sure the code runs without error, and then making sure it run correctly. The devil is in the details.
Here I list the common beginners’ mistakes so that you can avoid them.
14.1 Common Error Messages
Beginners frequently come across the following five error messages - NameError, SyntaxError, IndentationError, IndexError and TypeError. Additionally, the users of dictionary often see KeyError. The following table shows how to track the source of error and fix it.
Error message | How to fix |
---|---|
NameError | Check whether the mentioned variable is defined |
SyntaxError | Check your python syntax. Did you miss a “:” ? |
IndentationError | Did you add proper indentation for a block ? |
TypeError | Are you using incorrect data type ? |
IndexError | Are you trying to access an undefined index in a list ? |
KeyError | Are you trying to access an undefined key in a dictionary ? |
The errors are explained in detail below with examples.
14.1.1 NameError
“NameError” appears, when a Python variable used in the code has not been defined. The error message usually mentions the undefined variable and the line number of the error. Therefore, NameError is relatively easy to fix.
Here is an example. The variable “xx” in line 2 is not defined.
x=7
print(xx)
Python 3.6.8 (default, Jun 11 2019, 01:21:42)
[GCC 6.3.0 20170516] on linux
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(xx)
NameError: name 'xx' is not defined
Mixing cases of variables is a common source of “NameError” in beginners’ codes. Python is case-sensitive and treats the variables “X” and “x” differently. Here is an example.
x=7
print(X)
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(X)
NameError: name 'X' is not defined
14.1.2 SyntaxError
SyntaxError means the Python code is not written following its correct syntax. Most often, missing “:” at the end of “if,” “for” and other compound statements is the source of SyntaxErrors for beginners.
for i in [1,2,3]
print(i)
Python 3.6.8 (default, Jun 11 2019, 01:21:42)
[GCC 6.3.0 20170516] on linux
File "main.py", line 1
for i in [1,2,3]
^
SyntaxError: invalid syntax
14.1.3 IndentationError
Python follows indentation rules strictly. IndentationError appears, when Python code does not follow the correct indentation rules. It can come from both missing expected indentation and adding indentation, when not needed.
Here are two examples.
x=1
print(x)
Python 3.6.8 (default, Jun 11 2019, 01:21:42)
[GCC 6.3.0 20170516] on linux
File "main.py", line 2
print(x)
^
IndentationError: unexpected indent
for i in [1,2,3]:
print(i)
Python 3.6.8 (default, Jun 11 2019, 01:21:42)
[GCC 6.3.0 20170516] on linux
File "main.py", line 2
print(i)
^
IndentationError: expected an indented block
14.1.4 IndexError/KeyError
IndexError means the list element being accessed does not exist. KeyError is similar in the context of dictionary.
x=[1,2,3]
print(x[4])
Python 3.6.8 (default, Jun 11 2019, 01:21:42)
[GCC 6.3.0 20170516] on linux
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(x[4])
IndexError: list index out of range
x={"aa": "AA", "bb": "BB"}
print(x["cc"])
Python 3.6.8 (default, Jun 11 2019, 01:21:42)
[GCC 6.3.0 20170516] on linux
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(x["cc"])
KeyError: 'cc'
14.1.5 TypeError
TypeError appears from mixing of different data types. In the following example, we asked to print “x(1),” and Python interpreted that as attempting to run function x with parameter 1. Since a list object cannot be run as a function, we got a TypeError.
x=[1,2,4]
print(x(1))
Python 3.6.8 (default, Jun 11 2019, 01:21:42)
[GCC 6.3.0 20170516] on linux
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(x(1))
TypeError: 'list' object is not callable
In the following example, we are trying to access a list by a floating point number instead of integer.
x=[1,2,3]
print(x[1.0])
Python 3.6.8 (default, Jun 11 2019, 01:21:42)
[GCC 6.3.0 20170516] on linux
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(x[1.0])
TypeError: list indices must be integers or slices, not float
14.2 Common Logical Flaws
Once you fix all errors you will find that the code runs to completion, but produces incorrect results. That means your code has flaws in logic, and it is not modeling the problem statement correctly. Let us look at some common logical mistakes made by the beginners.
14.2.1 Using Loops Incorrectly
Let us say we like to print the elements of a list in correct order.
The following code does not work -
x=[1,4,3,0,2]
for i in x:
print(x[i])
The following code works -
x=[1,4,3,0,2]
for i in range(len(x)):
print(x[i])
Many students make the mistake of writing the first code, when they intended to use the second. This mistake is common and hard to debug, especially when the code has additional steps.
Here is another example.
numbers=[23, 4, 5, 6,7, 12,2]
highest=0
for i in numbers:
if i>highest:
highest=i
print (highest)
numbers=[23, 4, 5, 6,7, 12,2]
highest=0
for i in range(len(numbers)):
if numbers[i]>highest:
highest=numbers[i]
print (highest)
Both codes correctly find the highest value from the list “numbers.” However, in the first case, “i” in the loop contains the values from the list, whereas in the second case, “numbers[i]” contains the values.
14.2.2 Exchanging Numbers
To replace two numbers, many beginners make the following mistake.
x=1
y=4
x=y
y=x
print (x,y)
Python executes one line at a time, and therefore the above code overwrites the value of x with y in line 4, and thus loses the original x. The ‘y=x’ statement in the following line copies that modified value of x into y. Therefore, at the end, both numbers equal 4.
14.2.3 Infinite Loop in ‘while’
Althought the following code is technically correct, it is functionally wrong. The while loop runs for ever, because i is never incremented inside while.
i=1
while (i<10):
print ("i times 7 is", i*7)
14.2.4 List of strings versus list as a string
x=["ATGC", "TGGG", "TAAA"]
y="ATGCTGGGTAAA"
print (x[0])
print (y[0])
“x” is a list of strings. Therefore, x[0] is “ATGC.” “y” is a string, and therefore y[0] is “A.”
14.2.5 Confusing Between readline() vs readlines()
In the following two examples, ‘lines’ is a list of lines, whereas ‘line’ is a string.
Therefore, ‘lines’ will not respond to string-processing commands.
f=open("genome")
lines=f.readlines()
f=open("genome")
line=f.readline()
14.2.6 Not Removing Newline after Reading Text from a File
f=open("genome")
line=f.readline()
print (line)
cleanline=line.strip()
print (cleanline)
14.2.7 Mixing up Between [] vs ()
Many students use “[],” when they intend to use “()” and vice versa. You use “[]” to get an element of a list, and “()” for a function.
14.2.8 Mixing up Between the Left and Right Sides of Expressions
A Python code evaluates an expression on the right side and then stores in the variable on the left side. Therefore, the following code works.
y = 1
x = (7+2)/y
The following code does not work.
y = 1
(7+2)/y = x
14.3 Debugging Concept
Use print statement to see what the program is doing.