Using ChatGPT to Debug Python Code
1 - Effectively Communicating with ChatGPT
How does Generative AI understand the context of a sentence, paragraph, or piece of code written? There are two answers! First, Generative AI has been trained and continues to train as it interacts with you and the rest of the world. The second answer is that it doesn’t understand. Sometimes Generative AI responds with an unexpected answer, AKA a hallucination. As we interact with Generative AI, we need to be clear in our intent and delivery to receive a valid and correct output. In this tutorial, we will be using ChatGPT to learn how to effectively use Generative AI to debug code.
Below is an example of how a small difference in language used can result in different outputs from ChatGPT. We asked ChatGPT why the Python code did not count from 1 to 10. See if you can identify the differences between the questions and see how ChatGPT responded.
Prompt:
class Test:
def print_the_number_ten(self):
ten = 10
print(ten)
test = Test()
test.print_the_number_ten() # Should print 10
Why does my Python code not count to 10?
Response:
The code you provided should indeed print the value 10. It defines a class `Test` with a method `print_the_number_ten()` that sets a local variable `ten` to 10 and then prints its value. An instance of the `Test` class is created and the `print_the_number_ten()` method is called on that instance, resulting in the output of `10` to the console.
Prompt:
class Test:
def print_the_number_ten(self):
ten = 10
print(ten)
test = Test()
test.print_the_number_ten() # Should print 10
Why does my Python code not iterate from 1 to 10 and print all numbers out?
Response:
The code you provided is not designed to iterate from 1 to 10. It simply sets a local variable `ten` to 10 and prints its value. To achieve a loop that iterates from 1 to 10 and prints each number, you can modify your code as follows:
class Test:
def print_numbers(self):
for i in range(1, 11):
print(i)
test = Test()
test.print_numbers()
In this updated code, the `print_numbers()` method uses a `for` loop with `range(1, 11)` to iterate from 1 to 10 (inclusive). On each iteration, it prints the value of `i`, which represents the current number in the loop.
When you run this code, it will output the numbers 1 to 10, each on a separate line.
The first question asked specifically about the value 10 and nothing in between, whereas the second question was more clear about the intent to iterate to from 1 through 10.
When using Generative AI, we must be clear on what the problem is and the goal we are trying to reach. If we are not receiving the expected answer, or the answer is incorrect, we try a different prompt in hopes of achieving a better result.
2 - Identify Errors Using ChatGPT
Now that we understand the fundamentals of interacting with ChatGPT, let’s use ChatGPT to help us identify and fix errors in Python code. In this section, we’ll use ChatGPT to fix any issues with the Calculator
class below.
class Calculator:def add(self, left, right):returnn left + rightdef subtract(self, left, right)return left - rightdef multiply(self, left, right):return left * rightdef divide(self, left, right):return left % right
Note: We could also run this code in an IDE or a terminal. If any syntax errors were found that we don’t understand, we could pass the same code to ChatGPT and it could provide us with a potential solution.
Prompt:
class Calculator:
def add(self, left, right):
returnn left + right
def subtract(self, left, right)
return left - right
def multiply(self, left, right):
return left * right
def divide(self, left, right):
return left % right
Are there any syntax errors with the code above?
Response:
Yes, there are syntax problems in your code. Here's the corrected version:
class Calculator:
def add(self, left, right):
return left + right
def subtract(self, left, right):
return left - right
def multiply(self, left, right):
return left * right
def divide(self, left, right):
return left % right
In the original code, there are a few issues:
1. In the `add()` method, there is a type with an extra 'n' character in the `return` statement. It should be `return left + right` instead of `returnn left + right`.
2. In the `subtract()` method, there is a missing colon `:` after the method definition. It should be `def subtract(self, left, right):` instead of `def subtract(self, left, right)`.
3. In the `divide()` method, there is a type in the return statement. Instead of using the modulus operator `%`, you might want to use the division operator `/` for regular division.
Amazing! ChatGPT not only fixed the errors but also corrected the logical error of modulo vs. division since we named our function divide()
. As you become more proficient in using Generative AI, ensure that the output it provides has the intended effect you are looking for.
3 - Examine Sections of Code Using ChatGPT
What if we want to iterate line by line through a section of code and identify and track the value of specific variables as the code is executed? Here is how you can make ChatGPT simulate code execution:
- Provide the context for the conversation
- Provide the code to ChatGPT and make sure it understands
- Tell ChatGPT you want to simulate execution on a specific line
- Enumerate through specific lines of code
1. Context:
Prompt:
I need you to debug Python code for me
Response:
Of course! I'll do my best to help you debug your Python code. Please provide the code you're experiencing issues with, along with a description of the problem you're facing.
2. Code:
Prompt:
Given this Python code:
'''
nums = []
for i in range(0, 10):
nums.append(i)
'''
Respond with YES if you understand the code.
Response:
Yes, I understand the code. The provided code snippet creates an empty list called `nums`. It then iterates through the numbers from 0 to 9 (inclusive) using the `range()` function. In each iteration, it appends the current number `i` to the `nums` list using the `append()` method. Therefore, at the end of the loop, the `nums` list will contain the numbers from 0 to 9.
Prompt:
Can you enumerate the lines of code?
Response:
Certainly! Here's the enumeration of the lines of code:
nums = []
for i in range(0, 10):
nums.append(i)
Line 1 initializes an empty list called `nums`. Line 2 starts a `for` loop that iterates over the numbers from 0 to 9 using the `range()` function. Line 3 appends each number `i` to the `nums` list using the `append()` method.
3. Simulate:
Prompt:
I want to simulate the loop that starts on line 2. When I say STEP you will execute one iteration of the loop. Respond with YES if you understand.
Response:
Yes, I understand. I will simulate the loop for you, executing one iteration at a time when you say "STEP".
Prompt:
Furthermore, let's keep track of the nums variable with every iteration. When I say STEP you will also print out the current value of the nums variable. Respond with YES if you understand.
Response:
Yes, I understand. In addition to simulating the loop, I will also print out the current value of the `nums` variable with each iteration when you say "STEP".
4. Enumerate:
Prompt:
STEP
Response:
Certainly! Since this is the first step, the `nums` variable is currently an empty list `[]`.
Prompt:
STEP
Response:
Certainly! After the second step, the `nums` variable contains the value `[0]`.
Prompt:
STEP
Response:
Certainly! After the third step, the `nums` variable contains the values `[0, 1, 2`].
We’ll stop iterating through all of them as you understand the point. I will, however, include the last bit of dialogue with ChatGPT.
Prompt:
STEP
Response:
Certainly! After the eleventh step, the `nums` variable contains the values `[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]`.
Prompt:
STEP
Response:
There are no further iterations because the loop has completed. The `nums` variables already contains all the numbers from 0 to 9.
Great work! We were able to use ChatGPT to enumerate through lines of code. It was able to explain the code and the variables’ values per iteration. Additionally, ChatGPT assisted in debugging code by executing lines of code, one at a time, to track variables as the code was executed.
4 - Conclusion
In conclusion, we went over how to communicate with Generative AI. Being clear in the problem set, goals, and intent is a must when working with Generative AI. We used ChatGPT to assist in identifying and correcting syntax and logical issues with the Calculator
class. Not only did it provide a solution for these issues, but ChatGPT also identified their cause, helping us to understand where we went wrong. Lastly, we were able to use ChatGPT to iterate through code segments and track variables in the process.
If you haven’t already, be sure to create a ChatGPT account and ask it the same questions we asked and see if you get the same, or similar, outputs. Or, you could take it a step further and slightly deviate from the questions we asked and see how different the answers are.
Check out this case study to practice using ChatGPT to debug code: Debug Python Code with ChatGPT Case Study
Author
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full team