design, write and debug programs that accomplish specific goals, including controlling or simulating physical systems; solve problems by decomposing them into smaller parts.

use logical reasoning to explain how some simple algorithms work and to detect and correct errors in algorithms and programs

4.6a

LO: To debug simple programs.

Let's look at a program that needs debugging:

#Terry's parcel weighs half a kilogram.
#Graham's weighs 300g.
#How much do they weigh together?

#declare variables for the key information
terry = 500g
graham = 300g

#define a function requiring two arguments
def add_weights(weight1, weight2): #seperate the arguments with a comma
    print(weight1 + weight2)
    return (weight1 + weight2) #remember to return a value, don't forget that space!

#call the function inputting the two variables as arguments
add_weights(terry, graham)

			

The first thing we should try to do is run the program in IDLE (but remember not all bugs are caused by typing mistakes - sometimes the program will run but give out incorrect or unexpected answers). Here we will get a syntax error that is caused when we have declared the variables terry = 500g and graham = 300g. If we remember back to 4.4a when we looked at variables we can see that 500g and 300g are not numbers so IDLE does not understand them.

#Terry's parcel weighs half a kilogram.
#Graham's weighs 300g.
#How much do they weigh together?

#declare variables for the key information
terry = 500
graham = 300

#define a function requiring two arguments
def add_weights(weight1, weight2): #seperate the arguments with a comma
    print(weight1 + weight2)
    return (weight1 + weight2) #remember to return a value, don't forget that space!

#call the function inputting the two variables as arguments
add_weights(weight1 + weight2)

			

This gives a NameError: name 'weight1' is not defined on the line where we call the function add_weights(weight1 + weight2). If we look where we have defined the function we see see that it is expecting two arguments in the parameters def add_weights(weight1, weight2): so what's wrong?
Remember that IDLE told us that the problem was NameError: name 'weight1' is not defined, if it is not defined then IDLE is expecting weight1 to be a variable name, a variable that has no value. If we look where we have declared our variables then we will see that the variable names are actually terry and terry so we can make the necessary changes and the code will run.



You will be able to find examples of programs that require debugging below (including a difficult one), or make your own ones.

Code Examples

Resources