Use ChatGPT for Python: build a small script you can run and understand

Give ChatGPT a small input, the exact result you want, and the Python environment you have. Ask for a complete script with a run command and an explanation of the important lines. Start with a task you can check by hand, then run the code locally before using it on a larger file.

For example, a stock file contains item IDs, descriptions and unit counts. You want a terminal report showing the total units and the IDs with zero stock. That is a useful first automation: it involves a real file, named columns, a loop and explicit number conversion, without needing a package installation or account connection.

Specify the file before asking for code

This original fictional CSV has three data rows:

item_id,description,units
0042,"Folder, blue",7
0420,Notebook,0
9001,Pencil,6

The expected total is 13 units, with 0420 as the only zero-stock ID. Item IDs are text, so their leading zeros must remain. The comma inside “Folder, blue” belongs to one quoted description; splitting each line at every comma would misread that row.

Python's standard-library CSV documentation describes DictReader for reading named columns and recommends opening CSV files with newline=''. Its reader normally returns strings, so convert the unit count deliberately rather than expecting an automatic number type.

Ask for a script suited to your machine

Open a terminal and check your available interpreter. On Windows, try py --version; on other setups, your command may be python3 --version or python --version. If none works, use the installation instructions for your system before treating a missing interpreter as a code defect.

Help me write and understand a small local Python script.
My OS and actual Python version command/output: [PASTE]
Goal: report total units and zero-stock IDs from stock.csv.
CSV columns: item_id, description, units.
Use Python's standard library only. Preserve item_id as text.
Units must contain nonnegative whole-number text; malformed or missing
units should stop the report with a row-specific error, not become zero.
The file is UTF-8. It may quote descriptions containing commas.
Read stock.csv beside the script, regardless of the working directory.
Do not edit or overwrite the CSV. Print results to the terminal.
Sample CSV and expected result: [PASTE THE FIXTURE AND EXPECTATION]

Return one complete script and the command for my environment. Explain
file paths, DictReader, integer conversion and the loop in plain language.
Identify assumptions. Do not claim you executed it on my computer.

OpenAI's prompting guide recommends describing the task and supplying relevant examples. An expected result gives you a way to check the generated code rather than judging it by how plausible it looks.

Read the script before running it

Save the sample as stock.csv and this authored implementation as stock_report.py in the same folder:

import csv
from pathlib import Path

source = Path(__file__).resolve().with_name("stock.csv")
total = 0
zero_ids = []

with source.open(encoding="utf-8", newline="") as handle:
    reader = csv.DictReader(handle)
    required = {"item_id", "description", "units"}
    if not required.issubset(reader.fieldnames or []):
        raise ValueError("CSV is missing required columns")

    for row_number, row in enumerate(reader, start=2):
        raw = row.get("units") or ""
        if not raw.isascii() or not raw.isdecimal():
            raise ValueError(f"CSV record {row_number}: invalid units")
        units = int(raw)
        item_id = row.get("item_id")
        if not item_id:
            raise ValueError(f"CSV record {row_number}: missing item_id")
        total += units
        if units == 0:
            zero_ids.append(item_id)

print(f"Total units: {total}")
print("Zero-stock IDs: " + (", ".join(zero_ids) or "none"))

Path(__file__) anchors the input to the script's location. DictReader makes row["units"] refer to the named field. The validation accepts ASCII decimal digits, including 0; negative values, blank values and decimal fractions are rejected. The record number is a logical CSV record number including the header, not necessarily a physical line number when a quoted field spans lines.

This is a deliberately small file contract. It does not check unique item IDs or reconcile stock movements, and it does not calculate when to reorder. Confirm those rules before adapting it to an operational inventory system.

Run a known case, then one failure

From that folder, use your confirmed interpreter command, for example:

py stock_report.py

The expected sample output is:

Total units: 13
Zero-stock IDs: 0420

Then change a copy of the fixture so one unit field says unknown. The program should stop with an error instead of printing a plausible total from incomplete information. Keep your original sample unchanged so you can rerun the 13-unit check after later edits.

If the command fails, send the actual traceback, interpreter version and smallest relevant sample back to ChatGPT. The debugging workflow covers that investigation. If the difficulty is deciding which source values are valid, settle those rules with the data-cleaning workflow before adding more Python.

Keep the script, input contract and checked fixture together. Once you can explain why a quoted comma stays inside one field and why 0420 remains text, you have a script you can maintain rather than a block of code you can only rerun.

Keep reading