Debugging – Common Mistakes not Producing an Error Message

Tracing code and printing the values of variables often identifies errors in short programs.  Below are examples of short code segments without compile-time or run-time errors generating the wrong output. The illustrated errors are quite common and the reasons are explained for each case.

Example 1

a = 4
b = 6
average = a + b / 2
print average

The code prints 7, but the student knows it should be 5.

Example 2

# Calculate the area of a triangle
base = 10
height = 5
area = (1 / 2) * base * height
print area

The code prints 0, but the student knows it should be 25.

Example 3

# Case Sensitive
name_list = ['Tom', 'John', 'Mike']
if "john" in name_list:
    print 'Yes'
else:
    print 'No'

The code prints ‘No’, but the student knows it should be ‘Yes’.

Example 4

# Misunderstanding about list index
name_list = ['Tom', 'John', 'Mike']
if name_list[2] == 'John':
    print 'Yes'
else:
    print 'No'

The code prints ‘No’, but the student knows it should be ‘Yes’.

Example 5

# No output generated
# This program is designed to compare two numbers and print out the larger one.
num1 = int(raw_input('Please input the first number: '))
num2 = int(raw_input('Please input the second number: '))

if num1 > num2:
    print num1
if num2 > num1:
    print num2

The code has no output if the two numbers input by the user is equal.

Example 6

# Nested Loops. Example 5: Find prime numbers.
# Example from http://www.pd4cs.org/example-5-find-prime-numbers/
n = 5
for i in range(2,n+1):
    count = 0
    for j in range(2,i):
        if(i % j ==0):
            count = count + 1
        if(count == 0):
            print i

The code prints 3 5 5 5, but the student knows it should be 2 3 5.