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
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
- 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
Step 1 — write a clear 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.
"""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
Write pytest tests for top_words, including one that checks punctuation is ignored.
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
Good prompts for Python (reuse these)
- "Add type hints and a short docstring to this function."
- "Make it handle an empty string without crashing."
- "Refactor this loop to a list comprehension, same behaviour."
- "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.
Ravindra Bagale's Tip – मराठी
AI कडे दोन short turns मध्ये एक Python function आणि pytest मागा: आधी function, नंतर tests. Chat वर विश्वास ठेवण्याआधी दोन्ही स्वतः चालवा.
Ravindra Bagale's Tip – हिंदी
AI से दो short turns में एक Python function और pytest माँगो: पहले function, फिर tests. 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.
नमस्कार मित्रांनो. आपण छोटा initials helper बनवू. आधी clear prompt लिहा. नंतर function चालवा. नंतर pytest चालवा. खालील नावं मुद्दाम बनवलेली practice-only नावं आहेत. ही खरी माणसं नाहीत. हे tests येथे दाखवलेली examples तपासतात. जगातील प्रत्येक name format सिद्ध होत नाही.
नमस्कार दोस्तों. हम छोटा initials helper बनाएंगे. पहले clear prompt लिखो. फिर function चलाओ. फिर pytest चलाओ. नीचे के नाम जानबूझकर बनाए गए practice-only नाम हैं. ये असली लोग नहीं हैं. ये tests यहाँ दिखे examples जाँचते हैं. दुनिया का हर name format सिद्ध नहीं होता.
Try this yourself: initials from a practice-only name
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.
- Create a project folder and open a terminal inside it.
- Create a venv: on macOS/Linux run
python3 -m venv .venv. On Windows runpy -3 -m venv .venv(orpython -m venv .venvif that is your Python 3 launcher). - Activate the venv: macOS/Linux
source .venv/bin/activate. Windows Command Prompt.venv\Scripts\activate.bat. Windows PowerShell.venv\Scripts\Activate.ps1. - Install pytest in the venv:
python -m pip install pytest(after activation,pythonshould be the venv interpreter). - Create a new file named
initials.pyand implementinitialsas described above. - Quick check:
python -c "from initials import initials; print(initials('Mira Quill'))"and expect the exact printoutMQ. - Save the tests below as
test_initials.pyin the same folder. - Run:
python -m pytest -q test_initials.pyand expect the exact output line3 passed.
Tests — save as 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):
terminalpython -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.
"""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
- Symptom:
"M Q"instead of"MQ"— Fix: join letters with"".join(...), not spaces, then re-run. - Symptom: extra spaces cause a bad result — Fix: use
full_name.split()so empty tokens are dropped, then re-run. - Symptom: empty string crashes — Fix: if there are no parts, return
"", then re-run the empty test.
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
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.