ChatGPT for Coding: From Zero to Working Scripts
Learn ChatGPT code generation with 5 real Python and JavaScript examples. Includes debugging prompts and how to fix errors step by step.
Get more content like this on Telegram!
Daily AI tips, notes & resources — free
ChatGPT for Coding: From Zero to Working Scripts
When I started learning to code a few years ago, I spent three hours debugging a Python script that had a single missing colon. Three hours. An experienced developer would have spotted it in 30 seconds.
That kind of experience is almost gone now. ChatGPT has changed what it means to be a beginner developer in a way that's hard to overstate — not because it writes all the code for you (it doesn't, not reliably), but because it collapses the feedback loop. You hit an error, you ask about it, you understand it, you fix it. What used to take an hour takes five minutes.
This guide is for beginners — people who can follow instructions but don't have years of syntax memorized. You'll get 5 working code examples across Python and JavaScript, a debugging method that actually works, and a clear picture of what ChatGPT is and isn't good at for coding tasks.
How to Ask ChatGPT for Code (The Right Way)
The biggest mistake beginners make: asking vague questions. "Write me a Python script" tells ChatGPT almost nothing. Good code prompts have four parts:
- Language and environment — "Python 3.11" or "JavaScript in a browser" or "Node.js"
- What the code should do — be specific and step by step
- What the input looks like — a sample value, a file format, a data structure
- What the output should be — exact format you expect back
The more concrete you are, the more immediately usable the code is. Vague prompts produce code that's technically correct but doesn't fit your actual situation.
5 Working Code Examples
Example 1: Python — Read a CSV and Calculate Averages
Prompt:
"Write a Python 3 script that reads a CSV file called 'sales_data.csv'. The CSV has columns: 'month', 'region', and 'revenue'. Calculate the average revenue per region and print a sorted summary. Include comments explaining each step."
Output:
import csv
from collections import defaultdict
# Dictionary to store total revenue and count per region
region_data = defaultdict(lambda: {'total': 0, 'count': 0})
# Read the CSV file
with open('sales_data.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
region = row['region']
revenue = float(row['revenue'])
region_data[region]['total'] += revenue
region_data[region]['count'] += 1
# Calculate averages
averages = {
region: data['total'] / data['count']
for region, data in region_data.items()
}
# Print sorted results (highest average first)
print("Average Revenue by Region:")
for region, avg in sorted(averages.items(), key=lambda x: x[1], reverse=True):
print(f" {region}: ${avg:,.2f}")
This is production-usable code. It handles the file reading, grouping, calculation, and formatted output — all in about 20 lines. The comments make it readable even if you don't know Python.
Example 2: Python — Rename Files in a Folder
Prompt:
"Write a Python script that renames all .jpg files in a folder called 'photos' by adding a date prefix (today's date in YYYY-MM-DD format) to each filename. So 'sunset.jpg' becomes '2026-05-29-sunset.jpg'. Don't overwrite files that already have the prefix."
Output:
import os
from datetime import date
folder = 'photos'
today = date.today().strftime('%Y-%m-%d')
for filename in os.listdir(folder):
if filename.endswith('.jpg') and not filename.startswith(today):
old_path = os.path.join(folder, filename)
new_name = f"{today}-{filename}"
new_path = os.path.join(folder, new_name)
os.rename(old_path, new_path)
print(f"Renamed: {filename} -> {new_name}")
print("Done.")
The "don't overwrite files that already have the prefix" detail — that's the kind of edge case beginners forget and that ChatGPT catches when you mention it explicitly.
Example 3: JavaScript — Fetch and Display API Data
Prompt:
"Write a JavaScript function that fetches data from the Open Trivia Database API (https://opentdb.com/api.php?amount=5&type=multiple) and displays the 5 questions in an unordered list in the HTML. Handle loading state and errors. Use async/await."
Output:
async function loadTrivia() {
const list = document.getElementById('trivia-list');
list.innerHTML = '<li>Loading questions...</li>';
try {
const response = await fetch(
'https://opentdb.com/api.php?amount=5&type=multiple'
);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
list.innerHTML = '';
data.results.forEach((item, index) => {
const li = document.createElement('li');
// Decode HTML entities in the question text
li.innerHTML = `<strong>Q${index + 1}:</strong> ${item.question}`;
list.appendChild(li);
});
} catch (error) {
list.innerHTML = `<li>Error loading questions: ${error.message}</li>`;
}
}
// Run when page loads
document.addEventListener('DOMContentLoaded', loadTrivia);
This is real, runnable JavaScript. The loading state, error handling, and HTML entity decoding are all things a beginner might not think to include — ChatGPT includes them because you asked for proper handling.
Example 4: Python — Web Scraping Basics
Prompt:
"Write a Python script using BeautifulSoup and requests to scrape the titles and URLs of all articles from the Hacker News front page (https://news.ycombinator.com). Print each title with its URL. Include pip install instructions in a comment."
Output:
# Install required packages:
# pip install requests beautifulsoup4
import requests
from bs4 import BeautifulSoup
url = 'https://news.ycombinator.com'
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
# Find all article title links
articles = soup.select('.titleline > a')
print(f"Top {len(articles)} articles on Hacker News:\n")
for i, article in enumerate(articles, 1):
title = article.get_text()
link = article.get('href', '')
# Handle relative URLs
if link.startswith('item?'):
link = f"https://news.ycombinator.com/{link}"
print(f"{i}. {title}")
print(f" {link}\n")
I ran this myself and it works. The relative URL handling at the bottom is the kind of detail that matters in real web scraping — and ChatGPT gets it right.
Example 5: JavaScript — Simple To-Do List Logic
Prompt:
"Write a JavaScript class called TodoList that stores tasks in an array. It should have methods to: add a task (with text and a priority of 'high', 'medium', or 'low'), mark a task complete by ID, delete a task by ID, and get all incomplete tasks sorted by priority. Include a sample usage at the bottom."
Output:
class TodoList {
constructor() {
this.tasks = [];
this.nextId = 1;
}
addTask(text, priority = 'medium') {
const validPriorities = ['high', 'medium', 'low'];
if (!validPriorities.includes(priority)) {
throw new Error('Priority must be high, medium, or low');
}
this.tasks.push({
id: this.nextId++,
text,
priority,
complete: false,
createdAt: new Date()
});
}
markComplete(id) {
const task = this.tasks.find(t => t.id === id);
if (task) task.complete = true;
}
deleteTask(id) {
this.tasks = this.tasks.filter(t => t.id !== id);
}
getIncomplete() {
const priorityOrder = { high: 0, medium: 1, low: 2 };
return this.tasks
.filter(t => !t.complete)
.sort((a, b) => priorityOrder[a.priority] - priorityOrder[b.priority]);
}
}
// Sample usage
const list = new TodoList();
list.addTask('Fix login bug', 'high');
list.addTask('Update README', 'low');
list.addTask('Review pull request', 'medium');
list.markComplete(2);
console.log('Incomplete tasks by priority:');
list.getIncomplete().forEach(task => {
console.log(`[${task.priority}] ${task.text}`);
});
This is clean, well-structured code that you can actually build on. The input validation and sample usage at the bottom are both things the prompt specified — and they both show up correctly.
The Debugging Method That Works
Here is the exact template I use when code doesn't work:
"I'm running this [Python/JavaScript] code and getting an error. Here is the code: [paste code]. Here is the error message: [paste exact error including traceback]. I expected it to [describe what you thought would happen]. What is causing the error and how do I fix it?"
The three-part structure — code, error message, expectation — gives ChatGPT everything it needs to diagnose the problem accurately.
What to paste: the full error including the traceback, not just the last line. "TypeError: 'NoneType' object is not subscriptable" is a fragment. The full traceback tells you which line caused it.
According to Python's official documentation, understanding the full error traceback is a fundamental skill. ChatGPT essentially teaches this skill by explaining each component when you ask it to.
Common Error Types and How to Ask About Them
Syntax errors: "My Python code shows a SyntaxError on line 14. Here is that section of code. What's wrong?"
Logic errors (code runs but gives wrong results): "This code runs without errors but produces the wrong output. It outputs [X] but I expected [Y]. Here's the code."
Import errors: "I'm getting 'ModuleNotFoundError: No module named X'. I installed it with pip. What might be causing this?"
Each framing gives ChatGPT different information and produces more targeted help.
What ChatGPT Is Not Good at for Coding
Being honest here saves you frustration:
Large codebases. ChatGPT works in conversation windows. It can't hold a 5,000-line codebase in context and reason about it holistically. For architecture-level questions, break the problem into smaller pieces.
Very new libraries. If a framework was released after ChatGPT's training cutoff, it may confidently write code using functions that don't exist. Check against the official docs.
Security-critical code. Authentication systems, payment processing, cryptography — ChatGPT can generate code that looks correct but has subtle vulnerabilities. Get these reviewed by someone with security experience.
For a broader look at AI coding tools, see our ChatGPT vs Claude comparison — the coding capabilities differ meaningfully between models.
Building From Here
Once you get a working script, here's how to keep improving:
Ask ChatGPT to explain what it wrote. "Can you explain what each function does and why you structured it this way?" This builds your understanding rather than just giving you code to copy.
Ask for improvements. "What would make this code more efficient?" or "How would I make this handle larger files?" — these questions extend the learning.
Our ChatGPT plugins guide includes Code Copilot GPT, which is specifically tuned for iterative coding conversations and worth exploring once you've used these basic approaches.
Conclusion
ChatGPT has made the beginner coding experience fundamentally different from what it was even two years ago. The barrier between "I don't know how to do this" and "I have working code" is much lower now — not because thinking is eliminated, but because the debugging feedback loop is so much faster.
The five examples in this guide are real, tested, runnable code. They cover file handling, data processing, API calls, web scraping, and object-oriented design — a decent breadth for beginner projects. Use them as templates, not just as one-offs.
The debugging method is probably the most valuable thing here for long-term growth. Code will always break. Having a reliable way to diagnose and fix it quickly — and to understand why it broke — is what actually makes you better over time.
Explore more AI productivity tools in our prompt engineering guide for the foundational techniques that make these coding prompts work.
Further Reading
- ChatGPT for YouTube Scripts: From Idea to Viral Video
- How to Use ChatGPT Code Interpreter for Data Visualization
- I Spent 100 Hours with ChatGPT-4o — Here's Everything I Learned
- ChatGPT for Legal Documents: Templates and Important Warnings
- ChatGPT Custom Instructions: The Secret Setting 90% of Users Miss
Frequently Asked Questions
AiTechWorlds Team
✓ Verified WriterThe AiTechWorlds team is passionate about AI, technology, and education. We create high-quality, research-backed content to help you learn, grow, and succeed in the modern digital world.
Related Articles
10 Advanced ChatGPT Prompting Techniques (Chain of Density and More)
Master advanced ChatGPT prompting with Chain of Density, Chain of Thought, Tree of Thoughts, role stacking, and 6 more expert techniques with real examples.
How to Use AI to Write a Compelling About Us Page (2026)
Use an AI about us page generator to craft a story, mission, and team section that builds trust. Includes 3 templates for startups, freelancers, and agencies.
How to Create AI-Generated Album Cover Art (Free Tools 2026)
Learn how to create AI album cover art for free using top tools in 2026. Genre-specific prompts, Spotify specs, and real tool comparisons inside.
5 AI Image Generators Specialized in Anime Style (2026)
Find the best AI anime generator for 2026. Compare NovelAI, Waifu Diffusion, Leonardo, and more with real accuracy tests and free tier details.