Python with AI Tutorial · Chapter 42 of 48
Python with AI means writing, fixing and understanding Python code together with an AI assistant such as ChatGPT, Claude or GitHub Copilot. You describe the task in plain language, the assistant drafts the code, and you run, test and refine it. Used well, it removes the blank-page problem and teaches you idioms faster than searching documentation.
The tools and where they fit
Chat assistants (ChatGPT, Claude, Gemini) are best for explaining concepts, drafting whole scripts and debugging pasted errors. Editor assistants (GitHub Copilot in VS Code, Cursor) complete code as you type. Terminal agents (Claude Code, Codex CLI) can read your whole project and edit several files at once. Beginners get the most from a chat assistant plus a real Python 3.12 install, because you learn by running the code yourself.
The prompt recipe
Vague prompts produce vague code. A good coding prompt states five things: the goal, the input data (with a sample), the exact output you want, constraints such as the Python version and allowed libraries, and how it will be used. Compare "write code to check invoices" with the prompt below.
Paste this prompt and compare the answer with the function in the next section.
Write a Python 3.12 function days_overdue(due, paid=None) that takes a due date and an optional payment date (both datetime.date). Return the number of days the invoice was paid late as an int; return 0 if it was paid on time or early. If paid is None use today. Standard library only, add type hints and two example calls.
Generate a function
A typical answer to the prompt above looks like this. Read it before running it: check that the edge case (paid early) is handled and that no library you did not ask for is imported.
from datetime import date
def days_overdue(due: date, paid: date | None = None) -> int:
end = paid or date.today()
return max((end - due).days, 0)
print(days_overdue(date(2026, 8, 1), date(2026, 8, 20)))
print(days_overdue(date(2026, 9, 10), date(2026, 9, 1)))
Output: 19 0
Refactor existing code
Paste code you already have and ask for a specific improvement: shorter, faster, more readable, or "use a list comprehension". Ask for one change at a time so you can see what moved.
orders = [("A-100", 250.0), ("A-101", 80.0), ("A-102", 1200.0)]
# before: a four-line loop appending to a list
# after the refactor request:
large = [order_id for order_id, total in orders if total >= 200]
print(large)
Output: ['A-100', 'A-102']
Explain code you did not write
Regular expressions, decorators and one-line pandas chains are ideal candidates for "explain this line by line". Run the snippet first so you can compare the explanation with the real behaviour.
import re
text = "Paid: INV-2026-0042, INV-2026-0043. Pending: INV-2026-0051"
print(re.findall(r"INV-\d{4}-\d{4}", text))
Output: ['INV-2026-0042', 'INV-2026-0043', 'INV-2026-0051']
Ask for an explanation that is pitched at your level.
Explain this Python regular expression to a beginner, one token at a time, then give two strings it matches and one it does not: r"INV-\d{4}-\d{4}"
Verify before you trust
AI code is a draft, not a verdict. The quickest check is a handful of assert statements with values you can compute by hand. Ask the assistant to write the tests too, then look for a case it forgot.
def apply_discount(price: float, pct: float) -> float:
if not 0 <= pct <= 100:
raise ValueError("pct must be between 0 and 100")
return round(price * (1 - pct / 100), 2)
assert apply_discount(100, 15) == 85.0
assert apply_discount(59.99, 0) == 59.99
assert apply_discount(80, 100) == 0.0
print("all tests passed")
Output: all tests passed
Spot hallucinated libraries
Assistants sometimes invent a package name or a function that sounds right but does not exist. Before you run pip install on an unfamiliar name, check it on pypi.org, and check what is already installed with importlib.
import importlib.util
for name in ["pandas", "openpyxl", "excelmagic"]:
found = importlib.util.find_spec(name) is not None
print(f"{name:10} {'installed' if found else 'NOT FOUND'}")
Output: pandas installed openpyxl installed excelmagic NOT FOUND
ACME Ltd and os.environ["API_KEY"] before you ask for help.GitHub Copilot in the editor
Copilot works from context. Write a clear comment or a function signature, pause, and it proposes the body in grey text; press Tab to accept or keep typing to reject. Because it only sees your open files, keep variable names descriptive and a sample of the data nearby.
# add 18% VAT to a list of net amounts and round to 2 decimals
def add_vat(amounts: list[float], rate: float = 0.18) -> list[float]:
return [round(a * (1 + rate), 2) for a in amounts]
print(add_vat([100, 250.5, 999]))
Output: [118.0, 295.59, 1178.82]
A working rhythm
- Describe the task with the five-part recipe and a data sample.
- Read the code. If a line is unclear, ask for an explanation before running it.
- Run it on the sample. Paste the full traceback back if it fails (see the debugging chapter).
- Add two or three asserts, then extend the code yourself.
- Ask for a review: "what could break this in production?"
Ask for options, not one answer
Assistants default to the first workable solution. Asking "show me two ways to do this and when each is better" exposes standard-library tools you may not know. Counting orders per region, for example, can be a loop with a dictionary or a single Counter; the second is shorter and comes with most_common() for free.
from collections import Counter
regions = ["North", "South", "North", "East", "North", "South"]
counts = Counter(regions)
print(counts)
print(counts.most_common(2))
Output:
Counter({'North': 3, 'South': 2, 'East': 1})
[('North', 3), ('South', 2)]
When the assistant offers a choice, ask it to name the trade-off in one sentence each: readability, speed, memory or dependencies. That habit turns generated code into a lesson instead of a copy-and-paste.
When to switch the assistant off
There are moments in learning where the assistant slows you down. Write your first loop, your first function and your first class by hand, because the mistakes you make there are the ones that teach syntax. Use AI when you are stuck for more than ten minutes, when you meet an unfamiliar library, or when you want a second opinion on code that already runs. Keep the balance and you will be able to judge the assistant instead of depending on it.
Common mistakes
- Accepting code you cannot explain. If you cannot say what each line does, ask before you keep it.
- Not stating the Python version or libraries, so the answer uses Python 2 prints or a package you do not have.
- Running
pip installon a name the assistant made up; look it up on PyPI first. - Pasting only the last line of an error instead of the whole traceback and the code around it.
- Sharing confidential data in the prompt.
Exercise
Ask an assistant for a function top_customers(sales, n) that takes a dict of customer name to total spend and returns the n biggest spenders as a list of (name, spend) tuples, largest first. Then write two asserts that prove it works and one that checks n larger than the dict length.
Show answer
def top_customers(sales: dict[str, float], n: int) -> list[tuple[str, float]]:
return sorted(sales.items(), key=lambda kv: kv[1], reverse=True)[:n]
data = {"Acme": 12000, "Bright Co": 4500, "Cobalt": 9800}
assert top_customers(data, 2) == [("Acme", 12000), ("Cobalt", 9800)]
assert top_customers(data, 1)[0][0] == "Acme"
assert len(top_customers(data, 10)) == 3
print(top_customers(data, 2))
Output:
[('Acme', 12000), ('Cobalt', 9800)]
Related chapters
FAQ
Which AI assistant is best for learning Python?
Any current chat assistant works for beginners. ChatGPT and Claude explain concepts well; GitHub Copilot is better once you write code daily in an editor. The habit of running and testing the code matters more than the brand.
Is code written by AI safe to use in my company?
Treat it as a draft from a junior colleague: read it, test it, and check licences for any library it introduces. Never paste secrets or customer data into the prompt.
Can I learn Python with AI without writing code myself?
Not really. You retain what you type, run and fix. Use the assistant to unblock and explain, then rewrite the solution in your own words.
Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.
Chapter 42 of 48 · Python with AI: all 48 chapters



