Debugging Your First Python Application
In this section:
Finding out the origin of the problem
Remember, in the previous tutorial you've solved the quadratic equation? Let’s play a little more with it, and calculate the roots of
3x2 + 5x + 6.
Oops... PyCharm reports a run-time error:
We’re getting a ‘ValueError: math domain error’. This means that we’re doing something which is mathematically impossible.
Let’s dig a little deeper into our code to find out what’s going wrong. We can use the PyCharm debugger to see exactly what’s happening in our code. To start debugging, you have to set the breakpoints first. To create breakpoints, just click the left gutter:
Next, right-click the editor background, and choose on the context menu. PyCharm starts the debugging session and shows the Debug tool window.
The Variables tab shows the entered values of the variables
a,b,c and the calculated value of the variable
d. Now remember, we got an exception in the line where we calculated
math.sqrt (d). We can see that the value of the discriminant
-47, calculating the square root of
-47 would result in an imaginary number. So we’ve found our problem.
To prevent our users from getting this exception again, let’s add an
if statement to check for a negative discriminant. If the discriminant is negative, that means that the equation the user has entered has no roots (it doesn’t cross the X-axis). So let’s just tell the user that in case we get a negative discriminant. To do that, select the discriminant calculation statements, and then press Ctrl+Alt+T ():
PyCharm creates a stub
if construct, leaving you with the task of filling it with the proper contents. Finally, it would be nice to have the whole calculation repeated more than once, so let's use the
Surround with action again: select the entire body of the function
demo and surround it with
while. You'll end up with this code:
import math class Solver: def demo(self): while True: a = int(input("a ")) b = int(input("b ")) c = int(input("c ")) d = b ** 2 - 4 * a * c if d>=0: disc = math.sqrt(d) root1 = (-b + disc) / (2 * a) root2 = (-b - disc) / (2 * a) print(root1, root2) else: print('This equation has no roots') Solver().demo()
Next, let's debug this script, and then run it again.
As it was said previously, the debugging session begins with putting breakpoints, and displays the debugging output in the Debug tool window.
The Debug tool window shows dedicated panes for frames, variables, and watches, and the console, where all the input and output information is displayed. If you want the console to be always visible, just drag it to the desired place.
Use the stepping toolbar buttons to step through your application:
As you step through the application, each reached breakpoint becomes blue:
Pay attention to the values that appear next to the variables in the editor: this is the inline debugging. This feature is enabled in the Debug tool window: