for i in range(4):
= 2 - i
x = 100 / x y
Error: ZeroDivisionError: division by zero
Usually people make mistakes. This is not any different when you write Python code. Finding and fixing mistakes or coding errors is called debugging or finding bugs.
The easiest method to find errors or computer-bugs is to put a lot of print()
statements into your code, so you can see how specific variable values change.
for i in range(4):
= 2 - i
x = 100 / x y
Error: ZeroDivisionError: division by zero
for (i in 0:3) {
x <- 2 - i
y <- 100 / x
}
Here our program throws an error message because at some point in our loop we attempt to divide by zero, which is not defined. This is pretty obvious in this example but let's assume that we have trouble spotting the mistake. What you can do now is you can add print()
statements into the loop so you can see how the values of the variables change:
You can now see how the variables change as the loop progresses and how the division by zero error happens eventually.
We next import the debugger:
for i in range(4):
import pdb; pdb.set_trace() # XXX BREAKPOINT
= 2 - i
x = 100 / x y
for (i in 0:3) {
browser() # Breakpoint
x <- 2 - i
y <- 100 / x
}
Called from: eval(expr, envir, enclos)
debug at <text>#4: x <- 2 - i
debug at <text>#5: y <- 100/x
debug at <text>#3: browser()
debug at <text>#4: x <- 2 - i
debug at <text>#5: y <- 100/x
debug at <text>#3: browser()
debug at <text>#4: x <- 2 - i
debug at <text>#5: y <- 100/x
debug at <text>#3: browser()
debug at <text>#4: x <- 2 - i
debug at <text>#5: y <- 100/x
This will stop the code in the line where you set the Breakpoint
. So the code will enter the loop with value i=0
and then stop the execution.
You can now inspect variable values from the command line. Type ?
and hit enter and you will see all the commands that you can now run.
n
it will simply execute the next line of code. You can step through the code line by line and observe exactly what changes in each step.cont
for continue it will run the code until it hits the Breakpoint
again in the second iteration of the loop. It will then pause again at i=1
so that you can inspect all the variables again from command line.Debug the following program:
=8
d1myvar = 80
2myList = [23, 'jim", my, 34]
for listItems in enumerate(2myList):
print('Element {} in my list is equal to {}'.format(listItems)