In this tutorial, we will debug a python file and runs it using PyCharm.

Prerequisites :

  • You have already installed PyCharm Community or Professional.
  • If you’re using MacOS or Linux, your computer already has python installed or else you can get it from python.org .

Finding the problem

Given below is a code having some errors. Let’s see what the code given below does –

It reads 2 numbers and display its addition, subtraction, division and multiplication results.

def num():
    value1 = input("Please enter first integer:\n")
    value2 = input("Please enter second integer:\n")

    a = int(value1)
    b = int(value2)
    print(f’You entered {a} and {b} ‘)
    print(f'Their addition is {a + b}')
    print(f'Their subtraction is {a - b}')
    print(f’Their division is {a / b}’)
    print(f'Their multiplication is {a * b}')


num()

We can try to run the code as we got a tick mark (syntax error free) with inputs 10 and 2.

Runs the code

Here we can see the code runs and is successfully executed.

Executed successfully

Next let’s rerun the code, input the numbers 10 and 0. PyCharm reports a runtime error: ZeroDivisionError

Zero division error occurs

Now let’s dig a deeper to know what is happening.

Right click on the script and select debug ‘filename’, a console appears at the bottom.

debug the code

Give the inputs as 10 and 0 to know what happens in that case. PyCharm starts to debug and executes the code line by line.

If you want to know output in a particular stage you can use break points. It pauses execution and gives the instant output.

Opens debug console

When PyCharm detects an error, it shows a thunder bolt error. Here it appears in the line 10. So, we’ve found our problem that is the division by zero is not possible.

Error found when debugged

Modifying the code after debug

In order to run the code without any errors, we can modify the code by introducing if – else condition for division.

def num():
    value1 = input("Please enter first integer:\n")
    value2 = input("Please enter second integer:\n")

    a = int(value1)
    b = int(value2)
    print(f'You entered {a} and {b} ')
    print(f'Their addition is {a + b}')
    print(f'Their subtraction is {a - b}')
    print(f'Their multiplication is {a * b}')
    if b == 0:
        print(f'Their division is 0 ')
    else:
        print(f'Their division is {a / b}')


num()

Now we can run the code.

Modified the code after debug and executed

It is executed without any errors.

And now we have debugged our code.

Happy coding ..!!

Author

Write A Comment