AI for Coding
AI assistants have changed how people write software. They explain unfamiliar code, write first drafts of functions, find bugs from an error message and suggest tests. Students learn faster with them, and professionals ship features sooner. But AI-written code can look perfect and still be wrong, insecure or call functions that do not exist.
In this lesson you will learn what AI does well in coding, how to write coding prompts, which kinds of tools exist, and the single most important habit: verify AI code with tests.
What AI is good at in coding
- Explaining code: "Explain this function line by line for a beginner."
- Writing small, well-defined functions: "Write a Python function that validates an Indian PIN code."
- Debugging: paste the error message and the code that caused it.
- Writing tests: "Write tests for this function, including edge cases."
- Translating between languages: "Convert this JavaScript function to Python."
- Reviewing: "Review this code for bugs, security problems and unclear names."
It is weaker at large designs it cannot see, at your project's unwritten rules, and at very new library versions released after its training cut-off.
Writing coding prompts
A good coding prompt includes the language and version, the goal, the inputs and outputs with examples, the constraints, and for bugs the exact error message:
Python 3.14. Write a function format_inr(amount: int) -> str that formats
whole rupees with Indian digit grouping: the last 3 digits, then groups of 2.
Examples: 1234567 -> "12,34,567", 999 -> "999", -12345 -> "-12,345".
Use only the standard library. Include a docstring and 5 test cases.Concrete examples of input and output (as in Examples & Few-shot Prompting) remove most misunderstandings.
Verify with tests: a real example
Suppose an assistant gave you this function. It looks reasonable, and it works on the first number you try. The tests below check it properly:
def format_inr(amount):
"""AI draft: Indian digit grouping, e.g. 1234567 -> 12,34,567."""
s = str(amount)
if len(s) <= 3:
return s
last3, rest = s[-3:], s[:-3]
groups = []
while len(rest) > 2:
groups.insert(0, rest[-2:])
rest = rest[:-2]
groups.insert(0, rest)
return ",".join(groups) + "," + last3
tests = {1234567: "12,34,567", 999: "999", 100000: "1,00,000",
-12345: "-12,345", -999: "-999", 0: "0"}
for value, expected in tests.items():
got = format_inr(value)
print(f"{'PASS' if got == expected else 'FAIL'} {value}: got {got!r}, expected {expected!r}")PASS 1234567: got '12,34,567', expected '12,34,567' PASS 999: got '999', expected '999' PASS 100000: got '1,00,000', expected '1,00,000' FAIL -12345: got '-,12,345', expected '-12,345' FAIL -999: got '-,999', expected '-999' PASS 0: got '0', expected '0'
The function fails for negative numbers: the minus sign is treated as a digit. A quick look would never have caught this, but a test with a negative number did. Now the fix is easy, either by you or by pasting the failing test back to the assistant:
def format_inr(amount):
"""Indian digit grouping for whole rupees, e.g. 1234567 -> 12,34,567."""
sign = "-" if amount < 0 else ""
s = str(abs(amount))
if len(s) <= 3:
return sign + s
last3, rest = s[-3:], s[:-3]
groups = []
while len(rest) > 2:
groups.insert(0, rest[-2:])
rest = rest[:-2]
groups.insert(0, rest)
return sign + ",".join(groups) + "," + last3
tests = {1234567: "12,34,567", 999: "999", 100000: "1,00,000",
-12345: "-12,345", -999: "-999", 0: "0"}
failures = [v for v, expected in tests.items() if format_inr(v) != expected]
print("All tests pass" if not failures else f"Failing: {failures}")All tests pass
The lesson: ask the AI for tests too, and add your own edge cases: zero, negatives, empty input, very large values, unusual characters. In larger projects, use a test framework such as pytest and run the tests after every AI change.
Debugging with AI
When something breaks, give the model everything it needs in one go:
This Python script crashes. Error message (copied exactly):
KeyError: 'phone'
File "students.py", line 14, in send_reminders
Here is the function and one sample record from students.json.
Explain the cause in 2 sentences, then show the smallest fix.Asking for "the smallest fix" stops the model rewriting your whole program, which makes the change easy to review.
Coding tools
AI coding help comes in three main forms:
| Kind | Examples | Best for |
|---|---|---|
| Chat assistants | ChatGPT, Claude, Gemini, Copilot | Explanations, small functions, learning |
| Editor assistants | GitHub Copilot in VS Code and other editors | Suggestions while you type, quick edits |
| Coding agents | Claude Code, GitHub Copilot's agent features | Multi-file changes that run tests and commands |
Coding agents can read your project, edit several files and run commands. That is powerful, so review every change they make (for example with git diff) before you commit it.
Common mistakes
- Copying code you do not understand. Ask the AI to explain it, and make sure you could explain it too.
- Skipping tests. AI code often works for the happy path and fails on edge cases.
- Trusting function names. Models invent plausible functions and options; check the official documentation.
- Breaking your college's rules. Follow your course's policy on AI use in assignments.
Key points
- AI is strong at explaining, drafting small functions, debugging, writing tests and reviewing.
- Good coding prompts give the language and version, goal, examples of input and output, constraints and exact errors.
- Always verify AI code with tests, including edge cases such as zero, negatives and empty input.
- Chat assistants, editor assistants and coding agents suit different jobs; review every change agents make.
- Check package names and documentation, and never share secrets in prompts.
Exercise
Ask yourself what other inputs could break format_inr. Extend the fixed version so that it also accepts amounts with paise as a float with two decimals, for example 1234567.5 should become "12,34,567.50" and -0.75 should become "-0.75". Write at least four tests.
Show solution
def format_inr(amount):
"""Indian digit grouping with paise, e.g. 1234567.5 -> 12,34,567.50."""
sign = "-" if amount < 0 else ""
rupees, paise = f"{abs(amount):.2f}".split(".")
if len(rupees) > 3:
last3, rest = rupees[-3:], rupees[:-3]
groups = []
while len(rest) > 2:
groups.insert(0, rest[-2:])
rest = rest[:-2]
groups.insert(0, rest)
rupees = ",".join(groups) + "," + last3
return f"{sign}{rupees}.{paise}"
tests = {1234567.5: "12,34,567.50", -0.75: "-0.75", 999: "999.00",
100000: "1,00,000.00", -12345.678: "-12,345.68"}
for value, expected in tests.items():
got = format_inr(value)
print(f"{'PASS' if got == expected else 'FAIL'} {value}: {got}")PASS 1234567.5: 12,34,567.50 PASS -0.75: -0.75 PASS 999: 999.00 PASS 100000: 1,00,000.00 PASS -12345.678: -12,345.68
Formatting with :.2f first gives exactly two decimal places (and rounds), and the sign is handled separately so the grouping only ever sees digits.
Quick Quiz
1. What is the most reliable way to check AI-written code?
Tests reveal bugs that look-and-feel checks miss.
2. What should a debugging prompt include?
The exact error and the code that caused it let the model find the real cause.
3. An AI suggests pip install for a package you have never heard of. What should you do?
Models can invent package names, and attackers publish malicious packages under such names.
4. What makes coding agents different from chat assistants?
Agents act on your codebase, so their changes need careful review.
Learn Generative AI with a mentor
Free lessons get you started. Our AI Training & Workshops training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
