26/12/2023
How to Use ChatGPT to Write Code? 10+ Prompts Included
Table of Contents
Learning how to use ChatGPT to write code isn’t about letting AI take over your job; it’s about making your workflow smarter, faster, and less repetitive. At AMELA Technology, we’ve used ChatGPT to build real production systems — from small Python scripts to full API modules — and what we’ve learned is simple: the results depend on how you ask. When you structure your prompts right and guide ChatGPT like a junior developer, it delivers surprisingly clean, testable, and even optimized code.
In this blog, you’ll find battle-tested example prompts and practical tips to get high-quality code without endless tweaking.
Why Use ChatGPT for Coding?
Honestly, if you’ve ever wrestled with a stubborn bug at 2 a.m., you’ll get why ChatGPT is a game-changer for developers. It’s like having that one genius teammate who never sleeps and always has a clean code snippet ready.
At AMELA Technology, we use ChatGPT daily — to brainstorm ideas, generate boilerplate code, refactor messy functions, or debug stuff that just won’t run. It doesn’t replace real dev work, but it turbo-charges it. You throw in a quick prompt, and boom — you’ve got a working draft in seconds.
What makes it truly powerful is how flexible it is. You can ask ChatGPT to:
-
Explain a function you don’t fully understand.
-
Generate boilerplate code for a new feature.
-
Debug a snippet that keeps throwing an error.
-
Optimize your existing code for readability or performance.
For us, it’s become less of a “cool AI trick” and more of a go-to coding buddy that keeps projects moving fast when things get messy.

How to Use ChatGPT to Write Code (Step-by-step Guide)
Here’s the workflow we use at AMELA to get useful, shippable code out of ChatGPT without spending hours cleaning it up.
1. Define what you need — clearly and specifically
The biggest mistake people make is asking vague things like “write a Python script” or “build a login system.” ChatGPT isn’t a mind reader — it performs best when you give a tight scope and clear parameters.
Before you hit enter, make sure your request includes these 5 basics:
-
Task – What exactly should it do? (e.g., “create an API endpoint that uploads an image to AWS S3”).
-
Tech stack – Specify language, framework, and versions (e.g., Node.js + Express, Python 3.11).
-
Inputs/outputs – Define what data it should handle and return.
-
Constraints – Mention performance, security, or dependency rules (e.g., “avoid external packages”).
-
Output format – Tell it what you want: a function, a class, or a complete file.
Pro tip: If your task takes more than three lines to describe, it’s too big. Break it into smaller chunks. ChatGPT works best in short sprints.
2. Ask for a plan first — then the code
When working with complex logic or multiple files, start by asking ChatGPT to outline its approach before writing code. For example:
“Before coding, give me a brief plan with the main functions, data flow, and test cases. Wait for my approval before implementation.”
This gives you a chance to catch mistakes early — wrong assumptions, missing steps, or overcomplicated logic. Once the plan looks good, you can say:
“Looks great. Now implement step 1 and include short inline comments.”
This two-step approach (plan → code) keeps your workflow predictable and your code cleaner.

3. Add context to your prompts
ChatGPT doesn’t know your project — you have to feed it just enough context to understand where the code fits. For example, instead of saying:
“Fix this function, it’s broken.”
Say this:
“Here’s the current code from
/routes/user.py. It throws aKeyErroron line 17 when creating a new user. Can you identify the issue and fix it without changing the API behavior?”
That one extra line of detail makes the output way more relevant.
You can also share:
-
Your file structure (so it knows where the file sits).
-
Error logs or stack traces.
-
Framework-specific details (like “this is a Django view” or “runs on React 18”).
Pro tip: If you’re integrating multiple parts, ask ChatGPT to output a unified diff — it’s easier to review changes.
4. Learn how to craft effective prompts
Here’s the real secret: good code starts with a good prompt. Think of your prompt as a mini technical spec. You don’t need to write an essay — just give enough clarity for ChatGPT to make smart assumptions.
A strong coding prompt should include:
-
Role: Set the context — “You are a senior TypeScript developer” or “You’re an expert in writing secure Python APIs.”
-
Task: Be direct — “Implement a function that sanitizes HTML input.”
-
Rules: Add conditions — “No external dependencies, follow PEP8 style, use async.”
-
Expected output: Tell it what form to return — “Output only the final code block.”
Here’s a real example we’ve used:
“You are a senior Python engineer. Implement a FastAPI POST endpoint
/api/normalizethat takes a JSON payload{text: str}and returns{cleaned_text: str}. Strip HTML tags, lowercase text, and remove extra whitespace. Use Python 3.11, FastAPI 0.110, and include 3 pytest tests. Return one complete code block.”
The difference between this and a generic “write an API” prompt is night and day. This one tells ChatGPT what, how, and in what form — leaving no room for guesswork.

5. Review, test, and iterate quickly
Treat ChatGPT like a teammate, not a vending machine.
-
Run the code locally after each response.
-
Paste back test failures or logs if something breaks.
-
Ask for fixes in small steps — “fix only the sanitize_text() function,” not “rewrite everything.”
If the first version works but isn’t clean, follow up with:
“Refactor for readability and performance but don’t change functionality.”
This keeps your codebase consistent and avoids the “AI rewrite chaos.”
6. Harden your code before deploying
Before merging or deploying, always ask ChatGPT for a quick security and performance audit. It can catch risky patterns like unescaped SQL queries, regex vulnerabilities, or inefficient loops.
You can say:
“Review this code for security risks — XSS, SQL injection, unsafe evals — and suggest safer alternatives.”
or
“Optimize this function for large inputs. Keep it O(n) time complexity if possible.”
The idea is to make ChatGPT double-check your work — like a built-in peer reviewer.
7. Control the output format
This sounds small, but it saves time: tell ChatGPT exactly how to present results.
-
“Return only the code block.”
-
“Output a diff showing only modified lines.”
-
“Explain the changes in one short paragraph.”
Clear output instructions keep your terminal clean and your copy-paste process painless.
Example ChatGPT Prompts for Coding You Can Copy and Use Right Away
Once you understand how to guide ChatGPT, prompts become your real superpower.
Below are ready-to-use examples that we’ve tested in real development workflows at AMELA Technology — from quick utilities to debugging and refactoring.
You can copy, tweak, or stack them depending on your project.
- Generate a Function or API Endpoint
Prompt:
You are a senior Python engineer.
Task: Implement a FastAPI POST endpoint `/api/normalize` that takes JSON {“text”: str} and returns {“cleaned_text”: str}.
Requirements:
– Remove HTML tags
– Convert to lowercase
– Trim extra whitespace
– Use Python 3.11 and FastAPI 0.110
– Include 3 pytest tests
Output: one complete code block + short explanation.
Why it works: clear scope, specific stack, edge cases, and test coverage — everything ChatGPT needs to deliver clean, runnable code.
- Debug an Existing Error
Prompt:
Here’s my current code and stack trace. The function `sanitize_input()` throws a `TypeError: expected bytes-like object, got ‘NoneType’` on line 22.
Goal: Fix the bug without changing the public API.
Explain the cause in 2 lines, then show only the corrected function.
Pro tip: Always say “without changing the public API.” It prevents ChatGPT from rewriting too much.
3. Refactor Code for Readability or Performance
Prompt:
Refactor the function below to improve readability and performance.
Rules:
– Keep output identical
– Reduce nesting
– Add short comments and type hints
– Keep complexity O(n)
After refactoring, explain your main improvements briefly.
Real-world use: Ideal when your junior dev hands over working but messy code. ChatGPT cleans it up in seconds.
- Write Unit Tests Automatically
Prompt:
Write 5 pytest tests for the function `calculate_discount(price, percent)` that cover:
– Normal case
– Zero or negative percent
– 100% discount
– Very large numbers
– Invalid inputs (None, str)
Return code only.
Why it’s useful: You’ll never “forget” edge cases again — ChatGPT spots them faster than manual brainstorming.
- Translate Code Between Languages
Prompt:
Convert this JavaScript function to Go.
– Keep the same behavior and variable naming
– Use idiomatic Go syntax
– Add basic error handling
– Include one example test
Real-world case: Perfect when migrating microservices or rewriting prototypes from JS to Go or Python.
- Generate a SQL Query Safely
Prompt:
You are a SQL expert.
Database: PostgreSQL 15.
Task: Get top 20 customers by revenue in the last 90 days, excluding refunded orders.
Output:
1. Safe parameterized SQL query.
2. Recommended index for optimization.
3. Brief explanation of why this query is efficient.
Why it works: Combines correctness + optimization + reasoning — ChatGPT becomes a part-time DBA.
- Create a Full API Client
Prompt:
Given the following OpenAPI JSON schema, generate a TypeScript client.
Requirements:
– Use fetch API (no Axios)
– Handle non-2xx errors
– Include retry(count, backoffMs) option
– Return one file named `client.ts`
Pro tip: Tell ChatGPT your file name — it helps keep your folder structure organized.
- Conduct a Quick Security Review
Prompt:
Perform a quick security review of the following Node.js code.
Check for:
– SQL or NoSQL injection
– XSS or unsafe eval()
– Missing input validation
– Hardcoded credentials
List each risk + short fix.
Provide updated code if necessary.
Even senior devs miss security details. This turns ChatGPT into your mini audit bot.
- Optimize for Speed or Memory
Prompt:
Analyze this Python function for time and space complexity.
Suggest a faster version that can handle input of 10^6 items.
Keep readability high and include a microbenchmark example.
Real-world use: We often use this for data-heavy tasks (like analytics pipelines or log processing).
- Generate Documentation or Comments
Prompt:
Add clear docstrings and inline comments to the code below.
Follow Google-style documentation format.
Keep comments concise, explaining logic—not syntax.
Pro tip: This works brilliantly for legacy code you inherited and don’t have time to rewrite.
Conclusion
To conclude, prompting ChatGPT to write code requires a thoughtful approach to maximize its effectiveness. By the following guide, you can guide the language model to generate accurate and relevant code. Remember to provide clear instructions, context, and constraints to improve the quality of the output. With these guidelines in mind, you can harness the power of ChatGPT, making your coding experience more productive and efficient.
At AMELA, we specialize in providing a comprehensive range of services, including AI app development, consulting, and NLP solutions. Embrace the transformative power of AI with AMELA and embark on a journey of innovation and growth. Contact us today to unlock your new opportunities!
Editor: AMELA Technology