Home β†’ ChatGPT & Prompt Engineering β†’ Module 6

Module 6: ChatGPT for Coding & Technical Work

Code generation, debugging, testing, and learning programming 10x faster

πŸ“… Week 2 πŸ“Š Intermediate

Error on line 47. Stack overflow. Segmentation fault.

You've been debugging for 3 hours. Coffee's cold. Deadline looming. The code should work, but...

Enter ChatGPT: paste your error, get fix in 30 seconds. But here's the catch β€” if you don't know how to ask, you'll get broken code that makes things worse.

This module teaches you to use ChatGPT as your senior developer pair programmer β€” whether you're a pro or learning your first language.

πŸ’‘ In this module, you'll master:

  • Code generation (functions, components, scripts)
  • Debugging strategies (error analysis, step-by-step fixes)
  • Test generation (unit tests, edge cases)
  • Documentation writing (docstrings, README files)
  • Code explanation & learning new languages
  • Refactoring & optimization techniques

πŸ’» Use Case 1: Code Generation

The Perfect Code Generation Prompt

🎯 Template Formula

Role: Expert [Language] developer Task: Write [function/class/component] that [does what] Requirements: - Input: [parameters, types, constraints] - Output: [return value, format] - Error handling: [what to check] - Edge cases: [scenarios to handle] - Style: [conventions, best practices] Include: - Type hints/annotations - Docstring/comments - Usage example - Test cases

Real Examples

Example 1: Python Function

Role: Expert Python developer following PEP 8 Task: Write a function to validate email addresses Requirements: - Input: email string - Output: Boolean (True if valid, False otherwise) - Check for: @ symbol, domain, no spaces, proper format - Handle edge cases: empty string, None, special characters Include: - Type hints - Docstring with examples - 5 test cases showing valid/invalid emails

ChatGPT Output:

import re
from typing import Optional

def validate_email(email: Optional[str]) -> bool:
    """
    Validate email address format.
    
    Args:
        email: Email string to validate
        
    Returns:
        True if email is valid format, False otherwise
        
    Examples:
        >>> validate_email("user@example.com")
        True
        >>> validate_email("invalid.email")
        False
        >>> validate_email(None)
        False
    """
    if not email or not isinstance(email, str):
        return False
    
    # Basic email regex pattern
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email.strip()))

# Test cases
test_cases = [
    ("user@example.com", True),      # Valid
    ("test.email@domain.co.uk", True),  # Valid with subdomain
    ("invalid.email", False),         # No @ symbol
    ("user @domain.com", False),      # Contains space
    (None, False),                    # None input
]

for email, expected in test_cases:
    result = validate_email(email)
    print(f"{email}: {result} (expected: {expected})")
                        

Example 2: React Component

Role: Senior React developer using TypeScript and modern hooks Task: Create a reusable Button component with loading state Requirements: - Props: label, onClick, isLoading, disabled, variant (primary/secondary) - Show spinner when isLoading is true - Disable button when loading or disabled - Variants use different colors - Accessible (ARIA labels) Include: - TypeScript interface for props - Styled with CSS-in-JS or className - Usage example with all variants

⚠️ Pro tip: Be specific about:

  • Language version: "Python 3.11" not just "Python"
  • Libraries: "Using pandas, not numpy" if you have preference
  • Style guide: "Follow Airbnb style guide" for JavaScript
  • Performance: "Optimize for speed" vs "Optimize for readability"

πŸ› Use Case 2: Debugging

The Debugging Framework
I'm getting this error: [PASTE FULL ERROR MESSAGE] Here's my code: ```[language] [PASTE RELEVANT CODE - include context] ``` Context: - What I'm trying to do: [Goal] - What's happening instead: [Actual behavior] - Environment: [Python 3.10, Django 4.2, etc.] - What I've tried: [Previous attempts] Please: 1. Explain what's causing the error 2. Provide fixed code 3. Suggest how to prevent this in future

Real Debugging Example

Error: TypeError: unsupported operand type(s) for +: 'int' and 'str' My code: ```python def calculate_total(prices): total = 0 for price in prices: total = total + price return total prices = ["10", "20", "30"] result = calculate_total(prices) print(result) ``` Context: - Trying to sum prices from user input - Getting type error - Prices are strings from a form What's the fix?

ChatGPT Response (example):

1. Root cause: You're trying to add strings to an integer. The prices list contains strings ("10") not integers.

2. Fixed code:

def calculate_total(prices):
    total = 0
    for price in prices:
        total += int(price)  # Convert string to int
    return total

# Or more Pythonic:
def calculate_total(prices):
    return sum(int(price) for price in prices)

# With error handling:
def calculate_total(prices):
    try:
        return sum(int(price) for price in prices)
    except ValueError as e:
        print(f"Invalid price format: {e}")
        return 0
                        

3. Prevention: Always validate and convert data types when accepting user input. Use type hints and validate at the boundary of your system.

πŸ§ͺ Use Case 3: Test Generation

Automated Test Writing
Generate unit tests for this function: ```python def calculate_discount(price, discount_percent, member_tier): """Calculate final price after discount. Args: price: Original price (float) discount_percent: Discount percentage (0-100) member_tier: 'bronze', 'silver', 'gold' (extra discount) """ if price <= 0: raise ValueError("Price must be positive") if not 0 <= discount_percent <= 100: raise ValueError("Discount must be 0-100") # Apply base discount discounted = price * (1 - discount_percent / 100) # Member tier bonus tier_bonuses = {'bronze': 0.05, 'silver': 0.10, 'gold': 0.15} if member_tier in tier_bonuses: discounted *= (1 - tier_bonuses[member_tier]) return round(discounted, 2) ``` Requirements: - Use pytest framework - Test all edge cases - Include parametrized tests - Test error conditions - Aim for 100% code coverage

ChatGPT generates: Complete test suite with ~15 test cases covering happy paths, edge cases, error conditions, and boundary values.

πŸ“š Use Case 4: Documentation Writing

Prompt 1: Docstrings

Add comprehensive docstrings to this code: ```python def process_data(data, filters, transform=True): result = [] for item in data: if all(f(item) for f in filters): if transform: item = item.upper() result.append(item) return result ``` Use Google-style docstrings with: - Brief description - Detailed explanation - Args with types - Returns with type - Examples - Raises (if applicable)

Prompt 2: README File

Create a README.md for my project: Project: Web scraper for e-commerce price comparison Tech stack: Python 3.10, BeautifulSoup, Selenium, SQLite Features: - Scrape prices from 5 websites - Store historical data - Price alerts via email - CLI interface Include: - Project description - Installation instructions - Usage examples - Configuration guide - Contributing guidelines - License (MIT)

Prompt 3: API Documentation

Document this REST API endpoint: Endpoint: POST /api/users Creates new user account Request body: - email (string, required): User email - password (string, required): Min 8 chars - name (string, optional): Display name Generate: - OpenAPI/Swagger spec - Example requests (curl + JavaScript fetch) - Response examples (success + errors) - Authentication requirements

πŸŽ“ Use Case 5: Learning & Code Explanation

Understanding Complex Code
Explain this code like I'm a beginner: ```python result = [x**2 for x in range(10) if x % 2 == 0] ``` Include: 1. What it does (plain English) 2. Step-by-step breakdown 3. Why use this vs a for loop 4. When to use this pattern

ChatGPT Response (example):

What it does: Creates a list of squared even numbers from 0 to 9.

Breakdown:

  • range(10) β†’ numbers 0 through 9
  • if x % 2 == 0 β†’ keep only even numbers (0, 2, 4, 6, 8)
  • x**2 β†’ square each one (0, 4, 16, 36, 64)
  • [...] β†’ collect into list

Why use this: More concise than a for loop, Pythonic, faster for simple operations

When to use: When transforming/filtering lists in one line. Avoid for complex logic.

Learning New Languages

I know Python. Teach me the equivalent in JavaScript. Python code: ```python # List comprehension numbers = [1, 2, 3, 4, 5] squared = [x**2 for x in numbers if x % 2 == 0] print(squared) ``` Show me: 1. JavaScript equivalent 2. Key differences between languages 3. Common gotchas for Python developers learning JS

♻️ Use Case 6: Refactoring & Optimization

Refactor this code to be more efficient and readable: ```python def find_duplicates(data): duplicates = [] for i in range(len(data)): for j in range(i+1, len(data)): if data[i] == data[j]: if data[i] not in duplicates: duplicates.append(data[i]) return duplicates ``` Improve: 1. Time complexity (currently O(nΒ²)) 2. Readability 3. Use Python best practices Explain what changed and why.

Refactored version:

from collections import Counter

def find_duplicates(data):
    """Find all duplicate elements in a list.
    
    Time complexity: O(n)
    Space complexity: O(n)
    """
    return [item for item, count in Counter(data).items() if count > 1]

# Or using set (if order doesn't matter):
def find_duplicates(data):
    seen = set()
    duplicates = set()
    for item in data:
        if item in seen:
            duplicates.add(item)
        else:
            seen.add(item)
    return list(duplicates)
                        

Changes:

  • O(nΒ²) β†’ O(n) using Counter
  • Removed nested loops
  • More Pythonic with list comprehension
  • Added docstring

⚑ Coding with ChatGPT: Best Practices

βœ… DO

  • Provide context: Language version, libraries, framework
  • Show error messages: Full stack trace helps diagnosis
  • Request explanations: "Explain why this works"
  • Ask for alternatives: "Show me 3 ways to do this"
  • Test generated code: Always run and verify
  • Iterate: "Make this more efficient" β†’ "Add error handling"

❌ DON'T

  • Copy-paste blindly: Understand before using
  • Trust for security-critical code: Review for vulnerabilities
  • Use outdated syntax: Specify version to get modern code
  • Skip testing: ChatGPT makes mistakes
  • Use for entire architectures: Better for functions/components
  • Ignore best practices: Request "follow PEP 8" or style guides

🎯 Hands-On Exercise: Build a Mini Project

πŸ“ Create a To-Do List CLI App

Challenge: Use ChatGPT to build a command-line to-do list manager.

Features:

  1. Add tasks
  2. Mark tasks complete
  3. List all tasks
  4. Delete tasks
  5. Save/load from file

Steps:

  1. Ask ChatGPT for project structure
  2. Generate each function with tests
  3. Debug any errors you encounter
  4. Request refactoring suggestions
  5. Generate documentation

Reflection:

  • How much faster was this vs coding alone?
  • What did ChatGPT excel at? Where did you need to step in?
  • Did you learn anything new about your programming language?

πŸš€ Code Faster with AI-Powered Tools

You've learned to code with ChatGPT. Now accelerate development with tools that integrate AI directly into your coding environment:

πŸ’»

Replit Pro - AI-Powered Code Environment

Replit | $20/month

Perfect for developers who need: Code directly in your browser with AI autocomplete, instant deployment, and collaborative coding. Built-in ChatGPT-like AI assistant that understands your entire project context.

πŸ’‘ Use Case: Building the to-do list manager from the exercise? Type "create function to add task" and Replit AI generates the code instantly. Ask "explain this error" and it debugs in real-time. No context switching to ChatGPT.

  • Ghostwriter AI: Real-time code completion that reads your entire project (smarter than Copilot)
  • Instant deployment: Build β†’ Deploy β†’ Share URL in seconds (no AWS/Heroku setup)
  • 50+ languages: Python, JavaScript, Java, C++, Goβ€”switch languages instantly
  • Why developers love it: ChatGPT workflow + coding environment = one tool
Try Replit Pro β†’ Free plan available, Pro unlocks AI features

πŸ’° Developer ROI

Coding speed: 3-5x faster with AI autocomplete + instant debugging
No DevOps: Save 2-4 hours/week on deployment, environment setup
Tool cost: $20/month (Replit Pro)
Time saved: 10-15 hours/month = $500-1,500 (at $50-100/hr dev rate)
ROI: Pay for itself in 30 minutes of saved setup time per month

πŸ“š Summary: Your Coding Toolkit

  • βœ… Code generation: Specify requirements, input/output, error handling, style
  • βœ… Debugging: Provide error + code + context + what you've tried
  • βœ… Tests: Generate comprehensive test suites with edge cases
  • βœ… Documentation: Docstrings, README files, API docs
  • βœ… Learning: Explain complex code, compare languages
  • βœ… Refactoring: Improve performance, readability, best practices

🎯 Key Takeaway: ChatGPT is your senior developer pair programmer β€” ask good questions, verify output, and learn from its suggestions. It accelerates coding 10x, but you're still the architect. Next: apply AI to business challenges.

πŸ“ Test Your Understanding

Question 1: What's the most important thing to include in code generation prompts?

Just the function name
Only the programming language
Requirements: input/output, error handling, edge cases, style guide
Nothing - ChatGPT figures it out

Question 2: When debugging, what should you provide to ChatGPT?

Just say "my code doesn't work"
Full error message + relevant code + context + what you've tried
Only the error message
Your entire codebase

Question 3: What's the biggest risk of using ChatGPT for coding?

Copy-pasting code without understanding or testing it
It's always too slow
The code never works
It only supports Python

Question 4: What should you specify for better code generation?

Nothing specific
Just the task
Language version, style guide, framework, and optimization goals
Only the output format

Question 5: How should you use ChatGPT for learning new programming languages?

Just ask it to write code, never understand it
Show code you know, ask for equivalent in new language with explanations
It can't help with learning
Only use official documentation

πŸš€ Next Step: ChatGPT for Business

You've mastered writing and coding. Now let's tackle business analysis, strategy, data insights, and decision-making β€” turn ChatGPT into your business consultant.

Coming up in Module 7: ChatGPT for Business & Analysis β€” market research, competitive analysis, data interpretation, strategy frameworks, and executive reporting.