Introduction
Whether you are a seasoned software developer, a data analyst who writes occasional Python scripts, or a business analyst who needs to query a database, ChatGPT has fundamentally changed how people write and fix code. It is available 24 hours a day, never judges your question, and can explain, generate, debug, and document code across dozens of programming languages.
This chapter covers the core coding workflows: generating code from a description, understanding unfamiliar code, tracking down and fixing bugs, writing unit tests, converting code between languages, and documenting functions. It closes with a worked example of using ChatGPT to iteratively fix a broken Python function.
1. Generating Code from a Description
The most common use case is: you know what you want code to do, but you do not want to write it from scratch.
The Anatomy of a Good Code Prompt
A strong code prompt includes:
- Language and version — Python 3.11, SQL (PostgreSQL), JavaScript (ES2022)
- What the code should do — in plain language
- Inputs and outputs — what goes in, what should come out
- Constraints or context — libraries available, performance requirements, coding style
- Example data — if relevant
Weak prompt:
Write Python code to process data.
Strong prompt:
Write a Python 3 function that reads a CSV file
named "sales.csv" containing columns: date,
product_name, units_sold, unit_price.
The function should:
1. Calculate total revenue (units_sold x unit_price)
for each row
2. Group by product_name and sum total revenue
3. Return a pandas DataFrame sorted by total revenue
in descending order
Use pandas. Include comments explaining each step.
Python Examples
File handling:
Write a Python script that reads all .txt files
in a folder, counts the word frequency across
all files, and prints the top 20 most common
words (excluding common stopwords like "the",
"a", "is").
API call:
Write a Python function that calls the Razorpay
API to fetch the last 10 payments for a given
merchant. Use the requests library. Handle
HTTP errors gracefully and return a list of
payment dictionaries.
Data processing:
I have a pandas DataFrame with a column called
"phone_number" that contains Indian mobile numbers
in inconsistent formats: some start with +91,
some with 0, some have spaces or dashes.
Write a function to clean this column so all
numbers follow the format: 10 digits, no spaces,
no prefix.
SQL Examples
Write a PostgreSQL query to find the top 5
customers by total order value in the last
30 days. Tables: orders (order_id, customer_id,
order_date, total_amount) and customers
(customer_id, name, email).
Write a SQL query using window functions to
calculate each salesperson's rank within their
region based on monthly sales. Include their
name, region, monthly sales, and rank.
JavaScript Examples
Write a JavaScript function that takes an array
of product objects (each with name, price, and
category properties) and returns a new array
filtered to only include products under ₹500,
sorted by price ascending.
2. Explaining Existing Code
When you encounter unfamiliar code — in a colleague's pull request, an open-source library, or a tutorial — ChatGPT can explain it line by line or at a high level.
High-Level Explanation
Explain what the following Python code does
in plain language. Assume I understand basic
Python but am not familiar with decorators
or metaclasses.
[paste code here]
Line-by-Line Explanation
Go through this function line by line and
explain what each line does. Flag any lines
that seem unusual or potentially buggy.
[paste code here]
Understanding a SQL Query
Explain this SQL query in plain English.
Tell me what data it returns and what each
JOIN and WHERE clause is doing.
[paste query here]
"What Does This Code Assume?"
This is an underused but powerful prompt:
What assumptions does this code make about
the input data? What would cause it to break
or return incorrect results?
[paste code here]
3. Debugging Error Messages
Debugging is where ChatGPT saves the most time. Instead of spending 30 minutes searching Stack Overflow, you can paste the error and the code and get a targeted explanation.
The Debugging Prompt Format
Always include three things:
- The full error message (copy it exactly)
- The code that produced the error
- A brief description of what you expected to happen
I am getting the following error when I run
my Python script:
--- ERROR ---
KeyError: 'total_revenue'
Traceback (most recent call last):
File "analysis.py", line 24, in calculate_summary
return df.groupby('product')['total_revenue'].sum()
--- END ERROR ---
Here is the relevant code:
[paste code]
I expected this to group the DataFrame by product
and sum the total_revenue column, but the column
seems not to exist. What is wrong?
Common Error Types and Prompts
| Error Type | What to Include in Prompt |
|---|---|
| Python exception | Full traceback + the function that raised it |
| SQL syntax error | Full query + the error message from the database |
| JavaScript TypeError | Console error message + the relevant function |
| Logic error (wrong output) | Code + expected output + actual output |
| Import/module error | Error message + your requirements.txt or environment details |
The "Explain Before Fixing" Approach
Rather than just asking for a fix, ask ChatGPT to explain the error first:
Before fixing this, explain why this error is
occurring and what it means. Then show me the fix.
This builds your understanding so you can avoid the same error in the future.
4. Writing Unit Tests
Unit tests are one of the most neglected parts of programming — they take time to write but save far more time in debugging later. ChatGPT writes them quickly and thoroughly.
Prompt:
Write unit tests for the following Python function
using the pytest framework. Cover:
- The happy path (normal input)
- Edge cases: empty input, None input, negative numbers
- A case that should raise an exception
[paste function here]
For JavaScript (Jest):
Write Jest unit tests for this JavaScript function.
Cover normal usage and at least 3 edge cases.
[paste function here]
Testing SQL Logic
I have a SQL stored procedure that calculates
commission for sales agents. Write test cases
(as SQL SELECT statements I can run) to verify
that:
1. An agent with ₹0 in sales gets ₹0 commission
2. An agent who exceeds the monthly target gets
the bonus multiplier applied correctly
3. NULL values in the sales column do not break
the calculation
[paste stored procedure here]
5. Converting Code Between Languages
You may need to port a Python script to JavaScript, translate a legacy PHP function to Python, or convert a pandas operation to SQL. ChatGPT handles this reliably for most standard operations.
Python to JavaScript:
Convert this Python function to JavaScript (ES2022).
Maintain the same logic and variable naming
conventions where possible. Add JSDoc comments.
[paste Python function here]
SQL to Python (pandas):
This SQL query runs against a database, but I
need to replicate the same logic in Python using
pandas because the data is now in a CSV file.
Convert it.
[paste SQL query here]
Python 2 to Python 3:
Update this Python 2 code to Python 3.
Highlight every change you made and explain why.
[paste Python 2 code here]
Caveats for Language Conversion
Some operations have no direct equivalent across languages or databases. Always ask:
Are there any parts of this conversion where
the behaviour might differ between the two
languages? Flag any edge cases I should test.
6. Documenting Functions
Well-documented code is far easier to maintain. ChatGPT can write docstrings, inline comments, and README sections for your code.
Python docstrings:
Write a Google-style docstring for this
Python function. Include: a one-line summary,
Args section, Returns section, Raises section
(if applicable), and one usage example.
[paste function here]
Inline comments:
Add clear inline comments to this code.
The target reader is a junior developer
who understands Python basics but is new
to pandas.
[paste code here]
README section:
Write a README section for this Python module.
Include: what it does, installation requirements,
a usage example, and a description of each
public function.
[paste module code here]
7. Worked Example — Iteratively Fixing a Broken Python Function
Let us walk through a realistic debugging session from broken code to working solution.
Scenario: You are a data analyst at a D2C (direct-to-consumer) startup in Mumbai. You have written a Python function to calculate the monthly average order value (AOV) from a CSV file. The function runs but produces incorrect results.
The broken function:
import pandas as pd
def calculate_monthly_aov(filepath):
df = pd.read_csv(filepath)
df['order_date'] = pd.to_datetime(df['order_date'])
df['month'] = df['order_date'].dt.month
monthly_aov = df.groupby('month')['order_value'].mean()
return monthly_aov
The problem: The output groups January 2024 and January 2025 together under month 1, so the average is wrong.
Step 1 — Report the Bug
This Python function is supposed to calculate
the monthly average order value (AOV) from a
CSV file with columns: order_date (YYYY-MM-DD),
order_id, order_value.
The function runs without errors, but it is
grouping January 2024 and January 2025 together
under "month 1", which means the average is wrong.
I need it to group by year AND month separately.
Here is the function:
[paste function]
Please fix this and explain what you changed.
ChatGPT fix:
import pandas as pd
def calculate_monthly_aov(filepath):
df = pd.read_csv(filepath)
df['order_date'] = pd.to_datetime(df['order_date'])
# Extract year-month as a period for correct grouping
df['year_month'] = df['order_date'].dt.to_period('M')
monthly_aov = df.groupby('year_month')['order_value'].mean()
return monthly_aov
ChatGPT explains: "The original code extracted only the month number (1–12), which caused data from different years to be grouped together. Using dt.to_period('M') creates a year-month period (e.g., 2024-01, 2025-01) that correctly distinguishes months across years."
Step 2 — Extend the Function
Good. Now I also want the function to:
1. Return the result as a DataFrame (not a Series)
with columns: year_month, avg_order_value, total_orders
2. Sort by year_month ascending
3. Round avg_order_value to 2 decimal places
4. Handle the case where the CSV file does not exist
— raise a clear error message instead of a cryptic
FileNotFoundError
Please update the function.
Step 3 — Write Tests
Now write pytest unit tests for the updated function.
Create a small test CSV in the test itself (using
io.StringIO so no file needs to exist on disk).
Test:
1. Normal data across two years
2. An empty CSV
3. A CSV where the file path does not exist
Step 4 — Add Documentation
Add a Google-style docstring and inline comments
to the final version of the function.
In four conversational turns, a broken function has become a tested, documented, production-ready utility. This is the iterative coding workflow that makes ChatGPT so valuable.
8. Best Practices for Coding with ChatGPT
Always test the code yourself. ChatGPT can produce code that looks correct but has subtle bugs. Run it, verify the output, and check edge cases.
Be specific about your environment. Specify Python version, library versions, and database type. A PostgreSQL query may not work in MySQL without changes.
Ask for explanations, not just code. If you do not understand why the code works, you cannot debug it when it breaks. Ask: "Explain why you wrote this line this way."
Use version control. Before asking ChatGPT to refactor your code, commit the current version. This gives you a safe rollback point.
Do not paste sensitive data. Never paste real customer data, API keys, passwords, or proprietary business data into ChatGPT. Use anonymised or synthetic data for examples.
Common Pitfalls
1. Accepting generated code without testing. ChatGPT sometimes produces code that looks plausible but fails on real data. Always run it against actual inputs before using it in production.
2. Vague error reports. "My code does not work" gives ChatGPT nothing to work with. Always include the full error message, the relevant code, and what you expected to happen.
3. Asking for code in the wrong language or version. ChatGPT will default to common versions if you do not specify. A Python 3.11 feature may break in Python 3.8. Always declare the exact language version.
4. Not asking ChatGPT to explain security implications. Generated code may have SQL injection vulnerabilities, insecure file handling, or hardcoded credentials. Ask: "Are there any security issues with this code?"
5. Pasting too much code at once. If you have 500 lines of code with a bug, isolate the function causing the issue and paste only that. Smaller context gets better, faster responses.
6. Skipping unit tests. It takes 2 minutes to ask ChatGPT for unit tests. Skipping them is the most common reason debugging sessions become 3-hour nightmares.
Practice Exercises
-
Write a prompt asking ChatGPT to generate a Python function that takes a list of Flipkart order dictionaries (each with
order_id,amount,status, anddate) and returns only the completed orders from the last 7 days, sorted by amount descending. Test the output. -
Find any SQL query online (or write a simple one yourself). Paste it into ChatGPT and ask for a plain-English explanation. Then ask: "What assumptions does this query make about the data, and what edge cases could cause it to return incorrect results?"
-
Write a deliberately buggy Python function (for example, an off-by-one error in a loop, or using
=instead of==in a condition). Paste it into ChatGPT with the error symptom and see if it finds the bug. Repeat with a more subtle bug. -
Take any Python function you have written or found online. Ask ChatGPT to: (a) add a Google-style docstring, (b) add inline comments, (c) write three pytest test cases. Evaluate the quality of each output.
-
Ask ChatGPT to write a JavaScript function that validates an Indian mobile number (10 digits, starting with 6, 7, 8, or 9). Then ask it to convert the same function to Python. Compare the two implementations and note any differences in how the regex or logic is expressed.
Summary
- A strong code prompt includes language and version, a clear description of what the code should do, input/output specification, and any constraints or available libraries.
- ChatGPT can explain code at a high level or line by line — use this to understand unfamiliar codebases or review pull requests.
- For debugging, always include the full error message, the relevant code, and what you expected — never just "my code is broken."
- Unit test generation is one of the fastest wins: ask for pytest or Jest tests covering happy path and edge cases immediately after writing a function.
- Language conversion works reliably for standard operations; always ask ChatGPT to flag edge cases where behaviour might differ between languages.
- The iterative debugging workflow — report the bug, fix it, extend it, test it, document it — is a repeatable system for turning broken code into production-ready functions.
- Never paste real credentials, customer data, or proprietary information into ChatGPT; always use anonymised or synthetic data.