Debugging in PyCharm

Let's see how we can implement various debugging practices while working with PyCharm. In this subsection, we will be working with the example that's included in the Chapter06/Debugging folder of this book's code repository. Specifically, we will consider the main.py file inside this folder, which contains the following code:

def change_middle(my_list):
print('Start function')
x = int(input('Enter a number: '))
my_list[1] = x
print('End function')


if __name__ == '__main__':
a = [0, 1, 2]
b = a

change_middle(a)

print(a)
print(b)

The preceding code is a simple Python program where we can explore the referencing mechanism in Python while learning about PyCharm's debugging functionalities. Either copy the code directly into a PyCharm project or import the file into your PyCharm.

In this file, we have a function called change_middle(), which takes in a Python list as the only parameter, asks for a number in the console using the input() function, and finally assigns that numerical value to the second element in the input list.

In the main scope of our program, we initialize a list of three numbers (0, 1, and 2) and assign it to the a variable. The a variable is assigned to the b variable so that the two have the same value (the list of three mentioned numbers). Next, we call change_middle() on a so that we can modify the second element in the list from the console. Finally, we print out the values of both a and b.

Without running the programming, let's hypothesize about the output that will be produced by our program. For example, you might—especially if you are familiar with C and C++—expect that, in the end, since we called change_middle() on a, the list will be [0, x, 2] (x is whatever we input in the console), and b will simply remain [0, 1, 2].

However, as we run the program, the output that we will obtain (if we were to input, say, 3 in the console when asked) is as follows:

Start function
Enter a number: 3
End function
[0, 3, 2]
[0, 3, 2]

We can see that both a and b have been modified, which contradicts our initial hypothesis. In the rest of this subsection, we will explore various debugging tools in PyCharm and attempt to debug this problem. (If you already know the cause of the aforementioned behavior, simply follow the discussions to learn about PyCharm's debugging features.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.94.171