The practical field guide

How to debug code with ChatGPT and check the fix

Show a small failing example, compare expected and actual behavior, and test a focused repair without hiding the error.

WhatsApp
More options
FacebookTelegramEmail
The short answer

Give ChatGPT the smallest example that still fails, the exact error or wrong result, and what should happen. Ask for a focused fix with an explanation. Run the failing case and nearby cases before treating the bug as solved.

Three-part visual method for How to debug code with ChatGPT and check the fix
Imagem: howusechatgpt.com

What you need before you start

Your code crashes, returns the wrong value, or behaves differently from what you expected.

Bring: The relevant code, a safe sample input, exact error text, expected result, and versions that could affect the failure.

Start with these steps

  1. Write down what should happen and what actually happens.
  2. Remove unrelated code while keeping an example that still shows the bug.
  3. Share that example and ask for the likely cause and smallest repair.
  4. Review the proposed change and run the original failing case.
  5. Check ordinary, empty, and invalid inputs where they matter, then record what passed and what remains unknown.

A prompt you can adapt

Copy, fill in the brackets, then review

Help debug this failure. Language and version: [details]. Expected result: [expected]. Actual result or exact error: [observed]. Small example: [code and input]. Explain the likely cause, propose the smallest fix, and give checks that would expose the old bug. Do not say you ran the code unless you actually did.

Replace every bracket with real information. Remove fields that do not affect your task.

What this looks like in practice

Teaching example: a list parser turns an empty input into an unwanted empty item. Decide that blank input should produce an empty list, then check blank input, normal input, and input with spaces.

A fix needs a failing case

Expected

State the contract

Observed

Reproduce the failure

Patch

Change the smallest cause

Test

Original and edge cases pass

Imagem: howusechatgpt.com

Begin with a failure you can point to

The most useful debugging request explains a gap: the program should do one thing, but does another. Write that gap before asking for help. 'My code does not work' can mean a crash, a wrong calculation, a missing file, a slow page, or a feature you have not built yet. Each problem needs different evidence.

Describe one failing input and the result you expected. For a form, that might be 'Submitting an empty name should show a message, but it creates an account.' For a calculation, it might be 'The total should be 15, but the function returns 150.' Copy the exact error when there is one, including the line information that is relevant.

ChatGPT can read the example, suggest causes, and propose a repair. A useful answer should connect the evidence to the cause. It should also explain how you can check the change. A confident explanation on its own is not proof that the bug is fixed in your program.

If you are new to coding, ask it to explain unfamiliar terms as they appear. You need enough understanding to know what the proposed change affects.

Provide the environment without dumping everything

Code runs inside an environment: a language version, packages, an operating system, and sometimes a browser or database. Include the parts that could affect the failure. A command that works in one shell may not work in another. A package function may have changed between versions. The installed version matters more than a guessed current version.

A compact prompt can say 'Python 3.x on Windows; no third-party packages; running this file from the terminal.' Replace that with your actual details. If a web page behaves differently in two browsers, say which ones and describe the difference. If the problem began after a package update, include the before-and-after versions when known.

Do not paste your whole machine setup or repository by default. Start with the relevant file and error. If ChatGPT asks for another file, ask what it needs from that file. This keeps the conversation focused and reduces the chance of sharing unrelated private data.

For package-specific claims, check the package's official documentation for the version you use. Ask for a source when the proposed fix depends on an option or function you cannot find.

Remove secrets before sharing code and logs

Code can contain passwords, access tokens, private URLs, customer records, or keys that allow access to a service. Logs may repeat those details even when the code does not. Look through the material before pasting it. Replace a secret with a clear placeholder such as YOUR_API_KEY, and use a small made-up sample instead of real customer data.

Preserve the structure that causes the bug. If a problem depends on an email being blank, use a fictional record with a blank email. If it depends on a filename containing a space, a harmless filename with a space can show it. Removing every detail can make the failure disappear, so change sensitive values while keeping the relevant pattern.

Do not share a full configuration file when only one setting matters. Tell ChatGPT which values you removed and whether the failure could depend on them. A placeholder for a private server cannot prove the server is reachable, so access problems may need checks in your own environment.

If a live secret was exposed, use the service's process to replace it and review access. Editing it out of a later message does not change the credential itself.

Make a small example that still fails

A small failing example removes the parts that are not needed to show the bug. This is often the most valuable step in debugging. Copy the relevant function into a temporary test file, use one safe input, and see whether the problem remains. If it disappears, something you removed is involved.

Reduce gradually. Remove one unrelated feature, run again, and keep the reduction only if the bug is still present. You may discover the cause yourself: perhaps the function works alone but receives a different value from the caller. That is useful evidence to bring to ChatGPT.

Keep the example complete enough to run. Include imports, sample data, and the call that shows the result. A function with no input or call can force the assistant to imagine how it is used. For an error across two functions, include both and explain how information moves between them.

Do not spend hours shrinking a simple issue. The goal is a clear example, not the smallest possible code in the world. If the failure depends on a database or browser state, document the steps and provide the relevant pieces instead.

Teaching example: a parser with unclear blank input

Here is a small teaching example, not a claim that this code was tested in your environment. The function takes comma-separated tags, removes spaces around each tag, and returns a list. The intended rule is that an empty or space-only input should return an empty list. Empty items between commas should also be ignored.

The original function removes spaces but keeps empty pieces. That matters because splitting an empty string gives a piece that is empty. A later step in an application might treat that piece as a real tag. The bug is easier to see when the intended behavior is stated before anyone changes the code.

Use the function, the sample calls, and the rule together when asking for help. If you wanted blank tags preserved for another reason, the correct repair would be different. Code is only wrong in relation to the behavior it is supposed to provide.

Teaching example — Python:
def parse_tags(text):
    return [part.strip() for part in text.split(',')]

print(parse_tags(''))              # Intended: []
print(parse_tags('red, blue'))     # Intended: ['red', 'blue']
print(parse_tags('red, , blue'))   # Intended: ['red', 'blue']

Prompt: Blank input should return an empty list, and empty pieces should be ignored. Explain where the unwanted empty items come from. Suggest a small fix that preserves the order of the remaining tags.

Ask for the cause before a large rewrite

For the parser, a useful explanation points to two steps: split creates pieces, and strip removes surrounding spaces without removing the piece itself. The repair needs to decide which stripped pieces to keep. There is no need to replace the whole application, add a library, or redesign the input form just to address this rule.

Ask ChatGPT to show the smallest change and explain what it changes. A possible teaching repair below stores each cleaned piece, then keeps it only when it is not empty. This is written in several lines so a beginner can follow it. A shorter version may also work, but shorter code is not automatically clearer.

Review any extra changes. If the assistant also sorts the tags, removes repeated tags, or converts letters to lowercase, it has changed behavior you did not request. Those might be useful features later, but they need their own decision. Ask to preserve order and letter case for this fix.

When a proposed patch is long, ask which lines are necessary to fix the observed failure and which are optional cleanup. Apply the necessary part first so the effect is easier to judge.

Teaching repair — expected behavior, not an executed test report:
def parse_tags(text):
    tags = []
    for part in text.split(','):
        cleaned = part.strip()
        if cleaned:
            tags.append(cleaned)
    return tags

Turn expected behavior into checks

A check should be able to expose the old bug. For this parser, checking only 'red, blue' is weak because the original function already handles that ordinary input. Blank input and an empty middle piece exercise the problem. Keep a normal case too, so a change that breaks ordinary behavior is visible.

Write the checks before accepting the fix when practical. In Python, assert compares a condition with what you expect; if the condition is false, it reports a failure. The sample checks below state the rule directly. They are suggested checks for the teaching example and are not a record of a test run.

Run them with the version and environment that matter to your program. If all checks finish without an assertion error, those cases passed in that run. That does not prove every possible input is correct. A function that can receive None, numbers, or a list needs a separate decision about how such inputs should be handled.

Save the failing case as a regression check: a check kept to catch this bug if it comes back. It should describe the intended result, not merely copy the structure of the new code.

Suggested checks for the teaching example:
assert parse_tags('') == []
assert parse_tags('   ') == []
assert parse_tags('red, blue') == ['red', 'blue']
assert parse_tags('red, , blue') == ['red', 'blue']
assert parse_tags('blue, red') == ['blue', 'red']

When the cause is uncertain, compare explanations

Some failures have several plausible causes. A missing file might mean the path is wrong, the working folder is different, or access is blocked. Ask ChatGPT for a short list of explanations ranked by the evidence you supplied. For each, request one check that would help tell it apart from the others.

Choose a small check that changes little. Printing the resolved file path can be more useful than reinstalling several packages. Inspecting the input type can be more useful than rewriting a calculation. Avoid changing many settings at once because a later success will not show which change mattered.

Report the actual result of each check. Say 'The resolved path points to this folder, but the file is in that folder,' rather than 'Still broken.' This gives the next response something new to work with. Keep private path details out if they are unnecessary.

Do not ask for a complete hidden thinking transcript. Ask for a brief explanation of the evidence, the likely cause, and the next useful check. Those are the parts you need to act on and evaluate.

Repair the explanation when the first patch fails

If the first change does not solve the failure, keep the original expected result and add the new evidence. Include the current code if you applied the patch, the exact output, and any changed error. Tell ChatGPT what you ran and what you did not run so it does not mistake a proposed check for a completed one.

A useful follow-up might be 'The blank input case now passes, but the real application sends None when the field is missing. The current function raises an error on None. Should the caller supply an empty string, or should the function handle a missing value? Explain the trade-off.' That asks a design question exposed by the test.

Do not silence the error by returning an empty result for every exception. That could hide damaged data or a different bug. Decide what invalid input means for the application. Sometimes the correct action is a clear error message; sometimes a default is appropriate.

If the conversation becomes crowded with abandoned versions, start a fresh chat with the current small example and a short note of completed checks. Carry forward the useful evidence, not every earlier guess.

Know when the task is actually finished

The bug is ready to close when the original failure is fixed, relevant nearby behavior still works, and you understand the important effect of the change. For a small standalone function, a few focused checks may be enough. For code used in a larger program, run the existing checks that cover its callers and the behavior you changed.

Record the problem, cause, changed behavior, and observed verification in plain language. For the parser, that might be 'Blank pieces were kept as tags. The function now removes them while preserving the order of real tags. Blank, ordinary, and empty-middle cases passed.' Use that statement only after observing those passes.

If you cannot run the code, say what remains unverified. A static reading can support a likely fix, but runtime behavior depends on the actual program and environment. Keep that difference visible when sharing the patch with someone else.

ChatGPT is most helpful when the conversation leaves you with a smaller problem, an understandable change, and a check you can repeat. The final code block is a proposed repair until the relevant behavior has been observed.

Prepare a clean reproduction before sharing more logs or files. Protect secrets in a coding question →

Check the result before you use it

  • Does the original failing input now produce the intended result?
  • Does the change keep ordinary behavior working?
  • Were test results observed in the relevant environment, or only suggested?

Watch for: Removing an error message or catching every exception can hide the problem while leaving the wrong result.

Sources and references

WhatsApp
More options
FacebookTelegramEmail