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.

Ravindra Bagale's Tip

Ask the AI for one Python function plus pytest in two short turns: first the function, then the tests. Run both yourself before you trust the chat.

Hello friends. We will build a tiny initials helper the same way we practice Python with AI help. First write a clear prompt. Then run the function. Then run pytest. The names below are invented practice-only names. They are not real people. Passing these tests checks the examples shown here. It does not prove every name format in the world.

Try this yourself: initials from a practice-only name

Environment (tested): these exercises were verified with Python 3.13.5 and pytest 9.2.0. Use Python 3.10+ (needed for list[float] style hints as written). Create a folder on your computer, open a terminal in that folder, then set up a venv and install pytest before you run tests.

Fictional practice data only. The names below are invented for teaching. They are not real people.

Your task: create initials.py with initials(full_name). Split on spaces, ignore extra spaces, and take the first letter of each word in uppercase. Example: initials("Mira Quill") returns "MQ". Example: initials(" pepin moss ") returns "PM". Empty or whitespace-only input returns "". Standard library only.

Also create test_initials.py from the tests block below.

HOW
  1. Create a project folder and open a terminal inside it.
  2. Create a venv: on macOS/Linux run python3 -m venv .venv. On Windows run py -3 -m venv .venv (or python -m venv .venv if that is your Python 3 launcher).
  3. Activate the venv: macOS/Linux source .venv/bin/activate. Windows Command Prompt .venv\Scripts\activate.bat. Windows PowerShell .venv\Scripts\Activate.ps1.
  4. Install pytest in the venv: python -m pip install pytest (after activation, python should be the venv interpreter).
  5. Create a new file named initials.py and implement initials as described above.
  6. Quick check: python -c "from initials import initials; print(initials('Mira Quill'))" and expect the exact printout MQ.
  7. Save the tests below as test_initials.py in the same folder.
  8. Run: python -m pytest -q test_initials.py and expect the exact output line 3 passed.

Tests — save as test_initials.py

test_initials.py
"""Tests for fictional initials practice."""
from initials import initials

def test_two_words():
    assert initials("Mira Quill") == "MQ"

def test_extra_spaces_and_case():
    assert initials("  pepin  moss ") == "PM"

def test_empty():
    assert initials("   ") == ""

Command and expected output (venv active):

terminal
python -m pytest -q test_initials.py
# -> 3 passed
Optional solution for initials.py (try yourself first)

Use this only after you attempt the task. Save or compare against your initials.py file.

initials.py
"""Fictional practice: initials from a full name."""

def initials(full_name: str) -> str:
    """Uppercase initials; extra spaces ignored; empty -> ""."""
    parts = [p for p in full_name.split() if p]
    return "".join(p[0].upper() for p in parts)

Troubleshooting this exercise

HOW
  1. Symptom: "M Q" instead of "MQ" — Fix: join letters with "".join(...), not spaces, then re-run.
  2. Symptom: extra spaces cause a bad result — Fix: use full_name.split() so empty tokens are dropped, then re-run.
  3. Symptom: empty string crashes — Fix: if there are no parts, return "", then re-run the empty test.
Practice label: inputs and names on this block are fictional teaching samples, not real people or accounts. Passing the listed tests checks those examples only.

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).