⚡0 XP🔥0

Prompts for Coding and Debugging

Lesson 11 of 19 ⏱ 5 min read ✎ 2 exercises ❓ 4-question quiz ▶ Runs Python

Use AI as a programming partner - generate code with clear specs, explain unfamiliar code, debug errors, write tests, refactor and review - and verify everything it produces.

AI as your programming partner#

AI assistants can save developers hours every day: writing boilerplate, explaining code, finding bugs, writing tests and documentation. But they work best when you stay in charge - giving precise specs and verifying results.

हिंदी में समझें

AI को एक तेज़ लेकिन कभी-कभी गलती करने वाले junior programmer की तरह इस्तेमाल करें:

  • उसे साफ़ specification दें (क्या input, क्या output, कौन-सी language/version, कौन-से edge cases)।
  • उसके code को खुद पढ़ें, चलाएँ और test करें - बिना जाँचे production में कभी न डालें।
  • Passwords, API keys या customers का personal data कभी भी public AI tool में paste न करें।

1. Generating code - write a spec#

Weak
Write a Python program for student marks.
Strong
Write a Python 3.12 function `grade_report(students)`.

Input: a list of dicts like {"name": "Asha", "marks": [78, 85, 92]}.
Output: a list of dicts with keys name, average (1 decimal), grade.
Grades: A (>=80), B (60-79.9), C (40-59.9), F (<40).

Requirements:
- Skip students with an empty marks list and print a warning for them.
- Don't use any external libraries.
- Add a docstring and type hints.
- Include 3 example calls with expected output, including one edge case.

Spec checklist: language & version, function name/signature, input format, output format, rules, edge cases, libraries allowed, style (comments, type hints), examples.

2. Explaining code#

Explain this code to a beginner who knows loops and lists but not
comprehensions or lambda. Go line by line, then summarise what the whole
function does in one sentence. Point out any bugs you notice.

```python
def top(d, n=3):
    return [k for k, v in sorted(d.items(), key=lambda x: -x[1])[:n]]
Great for: legacy code, code from colleagues, Stack Overflow answers, interview preparation.

## 3. Debugging - give the full picture

Include **all four**:

1. The code (the relevant part, not your whole project)
2. The **complete** error message / traceback
3. What you expected to happen
4. What you already tried

```text
My Flask route returns 500. Expected: JSON list of courses.

Error:
  File "app.py", line 42, in courses
    return jsonify([c.to_dict() for c in rows])
AttributeError: 'tuple' object has no attribute 'to_dict'

Code:
<code>
rows = db.execute("SELECT * FROM courses").fetchall()
return jsonify([c.to_dict() for c in rows])
</code>

I'm using sqlite3 directly, not SQLAlchemy. Explain the cause and give the fix.
Tip

Ask "Explain the cause first, then give the fix". Understanding the cause helps you avoid the same bug next time - and lets you judge whether the fix is right.

4. Writing tests#

Write pytest tests for the function below. Cover: normal cases, empty input,
negative numbers, and very large lists. Use descriptive test names.
Don't modify the function.

<code>
...
</code>

5. Refactoring and code review#

You are a senior Python reviewer. Review the code below for:
1. Bugs and edge cases
2. Readability and naming
3. Performance
4. Security (SQL injection, unsafe input handling)

Give a prioritised list (High / Medium / Low), then the improved code.
Keep the same function signatures.

6. Converting and learning#

  • "Convert this JavaScript function to Python, keeping the same behaviour."
  • "Rewrite this loop using a list comprehension and explain the difference."
  • "Give me 5 practice problems on Python dictionaries, increasing difficulty, without solutions."
  • "I'm learning SQL JOINs. Quiz me one question at a time and explain my mistakes."

7. Documentation#

Write a README for this project with: what it does, installation,
how to run, configuration (environment variables), and an example.
Audience: other developers on my team.

Verify everything#

Common Mistake

AI-generated code can:

  • use functions or library versions that don't exist or are outdated,
  • pass simple cases but fail edge cases,
  • contain security issues (SQL injection, hard-coded secrets, no input validation),
  • look correct but have subtle logic errors.

Always run the code, test edge cases, and read it before using it.

A quick habit: when AI gives you a function, ask it for test cases too - then actually run them:

▶ Try it YourselfPython
Ctrl + Enter to run

Privacy and security#

  • Never paste passwords, API keys, tokens, database URLs with credentials.
  • Remove or fake customer names, phone numbers, Aadhaar/PAN and other personal data.
  • Check your company's policy on which AI tools are allowed for work code.

Summary#

  • Give AI a full spec: language, signature, inputs/outputs, rules, edge cases, style.
  • For debugging include code + full traceback + expected behaviour + what you tried; ask for the cause first.
  • Use AI for tests, reviews, refactoring, explanations, conversions and docs.
  • Always run, test and review AI code; never share secrets or personal data.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Write the function the spec describes

Practise reading a spec - the kind you'd give an AI. Implement it yourself:

Spec: mask_email(email) keeps the first character of the username and the full domain, replacing the rest of the username with *. "ravi.kumar@gmail.com" → "r*********@gmail.com". If there's no @, raise ValueError.

2

Fix the bug (as an AI would explain it)

This function should return the average of a list but crashes on an empty list and gives wrong results. Fix it: return 0 for an empty list, otherwise the correct average.

Quick Quiz

Q1.

What should a good code-generation prompt include?

Q2.

When asking AI to fix an error, what is most important to include?

Q3.

Which is a safe practice when using AI-generated code?

Q4.

What should you NEVER paste into a public AI tool?