Ravindra BagaleCourses & study guides Track your progress
AI CODING ASSISTANTS · CHAPTER 3

How to Code in Python Using AI

Tell the AI what the function should do, read the code it writes, run it, and add a quick test. This chapter uses a small, real example that was actually run and tested.

In short: write a clear prompt with an example, let the assistant write the Python, then read, run and test it. Below is a working, tested sample.

Why Python first

WHY

Python is easy to read and the AI models know it very well. It is the best language to learn AI-assisted coding. The same steps work for any assistant (Copilot, Claude, ChatGPT, Gemini, local Ollama).

What you need

WHAT
  • Python 3 installed (python --version).
  • An editor with an AI assistant — e.g. VS Code + Copilot (see the setup guide).
  • pytest for tests: pip install pytest.

The project pattern, top to bottom

1 · Describe the function plain words + example 2 · AI writes the code you read every line 3 · Run it on an example check the output 4 · Ask AI for a test pytest 5 · Run the test green = keep it

Step 1 — write a clear prompt

HOW
COPY THIS PROMPT

Write a Python function top_words(text, n=3) that returns the n most common words in a string, lowercase, ignoring punctuation. Use only the standard library. Example: top_words("the cat sat on the mat the cat", 2) should return [("the", 3), ("cat", 2)]. Only return the code.

Step 2 — the code the AI writes (tested here)

Save it as wordcount.py. This exact version was run and passed its tests.

wordcount.py
"""Count words in a text file. Built with an AI assistant, then tested."""
from collections import Counter
import re


def top_words(text: str, n: int = 3):
    """Return the n most common words (lowercase), ignoring punctuation."""
    words = re.findall(r"[a-z]+", text.lower())
    return Counter(words).most_common(n)


if __name__ == "__main__":
    import sys
    data = open(sys.argv[1]).read() if len(sys.argv) > 1 else "the cat sat on the mat the cat"
    print(top_words(data))

Step 3 — run it

python wordcount.py
# -> [('the', 3), ('cat', 2), ('sat', 1)]

Step 4 — ask the AI for a test, then run it

FOLLOW-UP PROMPT

Write pytest tests for top_words, including one that checks punctuation is ignored.

test_wordcount.py
from wordcount import top_words


def test_top_words():
    assert top_words("the cat sat on the mat the cat", 2) == [("the", 3), ("cat", 2)]


def test_ignores_punctuation():
    assert top_words("Hi, hi! HI.", 1) == [("hi", 3)]
pip install pytest
pytest -q
# -> 2 passed
Rule: green tests are your proof. If a test fails, paste only the failing lines back to the AI and ask for a fix.

Good prompts for Python (reuse these)

  1. "Add type hints and a short docstring to this function."
  2. "Make it handle an empty string without crashing."
  3. "Refactor this loop to a list comprehension, same behaviour."
  4. "Explain this error and fix it:" + paste the error.

Watch out (common AI mistakes in Python)

  • Made-up libraries or functions — check imports actually exist.
  • Wrong edge cases — empty input, zero, very large numbers.
  • Old APIs — a function name may have changed; check the docs.
  • Never paste secrets or real data into a cloud assistant.

Quick quiz

1. What three things make a good code prompt?

The goal, the inputs/output, and a small example.

2. How do you prove AI Python code works?

Run it, and run a pytest test that passes.

3. What is a common AI mistake to check for?

Made-up libraries or functions that do not exist — verify imports.

4. What should you never paste into a cloud assistant?

Secrets or real customer data.

Save tokens and money

SMART AI USE

Ask for one function at a time and say "only the code". Reuse a working prompt as a template. Use a local model (Ollama + Continue) for free, private practice. See more AI Coding guides.

Save these cards

INTERVIEW CARDAI Coding

How do you code in Python with AI safely?

Answer: describe the function with an example, read the AI code, run it, and add a pytest test before trusting it.
Key line: AI can invent libraries — always check imports and run the code.
Ravindra Bagale · ravindrabagale.com/ai-coding
REVISION CARDAI Coding

Python with AI in 3 ideas

1 Prompt: goal + inputs + output + an example.
2 Read + run: never trust code you have not run.
3 Test: ask for a pytest test and run it.
Ravindra Bagale · ravindrabagale.com/ai-coding
More in this course: the same pattern works for JavaScript, Java, Go, SQL and more (coming in this section).