12 Prompts for Python Code Generation: From Simple Scripts to FastAPI

12 Prompts for Python Code Generation: From Simple Scripts to FastAPI

AI-powered code generation has evolved from a curiosity into a real productivity tool. Over the past year, developers have used prompts to generate everything from data-cleaning scripts to microservices. However, getting high-quality Python code from an AI assistant is not about typing a random request. It depends on the structure and specificity of your prompt. In this article, we break down 12 prompts that cover the whole spectrum: basic scripts, refactoring, web scraping, asynchronous programming, and complete FastAPI applications.

Each prompt is presented with a concrete use case, the exact prompt text, and a sample output. You can copy these prompts, adapt them to your project, and use them with any capable large language model (LLM) such as GPT-4, Claude, or Gemini. The examples are designed to be runnable with minimal changes.

Before we jump into the list, let's look at a few principles from OpenAI's Prompt Engineering Guide. They advise to "make your instruction as specific as possible" and to "use external tools" when needed. For code generation, this means including the library names, the desired function signatures, and error handling requirements. The prompts below follow that advice.

The Anatomy of a Good Code Prompt

A useful code-generation prompt contains five elements:

  1. Role: "You are a senior backend developer." This sets the tone and quality.
  2. Task: A clear description of what to build.
  3. Context: Information about the environment, input data, and constraints.
  4. Examples: Expected output or usage details.
  5. Format: Whether you need a single file, a project structure, or a README.

When you mention specific libraries like pytest, httpx, or SQLAlchemy, the model can produce code that matches current best practices.

Basic Prompts

1. Generate a CSV Processing Script

Use case: You have a CSV file and need a quick summary of its numeric columns without installing pandas.

Prompt:

You are an expert Python developer. Write a Python script that reads a CSV file located at 'data.csv'. The script should print the number of rows, the names of all columns, and the mean, min, and max of each numeric column. Use only the standard library. Add clear comments and handle the case where the file doesn't exist.

Example output:

import csv
import os
import sys

def process_csv(path):
    if not os.path.exists(path):
        print(f"Error: file '{path}' not found.", file=sys.stderr)
        sys.exit(1)

    with open(path, newline='') as f:
        reader = csv.DictReader(f)
        rows = list(reader)

    if not rows:
        print("The CSV file is empty.")
        return

    print(f"Total rows: {len(rows)}")
    print("Columns:", ', '.join(reader.fieldnames))

    for col in reader.fieldnames:
        try:
            values = [float(row[col]) for row in rows if row[col] != '']
        except ValueError:
            continue

        if values:
            print(f"{col}: mean={sum(values)/len(values):.2f}, min={min(values)}, max={max(values)}")

if __name__ == "__main__":
    process_csv("data.csv")

Explanation: The prompt deliberately asks for the standard library, which is a good practice if you don't want to add dependencies. Specifying the exact statistics and error handling gives you code that is robust enough for a production script.

2. Recursive Factorial With Validation

Use case: You are learning recursion or need a mathematically sound factorial function for an algorithm challenge.

Prompt:

Write a Python function to compute the factorial of a non-negative integer n. Use recursion. Add a docstring, use type hints, and include a check for invalid input (negative or non-integer). Use Python's final syntax.

Example output:

def factorial(n: int) -> int:
    """Compute the factorial of a non-negative integer n recursively."""
    if n < 0 or not isinstance(n, int):
        raise ValueError("n must be a non-negative integer")
    if n == 0:
        return 1
    return n * factorial(n - 1)

Explanation: Type hints and input validation are often omitted in casual prompts. By including them, you get code that is immediately acceptable for a code review.

3. Refactoring Procedural Code into a Class

Use case: You have a small script that you want to turn into a reusable service.

Prompt:

Take the following procedural Python code and refactor it into a class-based solution. The class should be called DataProcessor. It should have methods for reading a file, cleaning data, and calculating an average. Preserve the original logic. Add type annotations and a docstring for each method.

Procedural code:
def read_and_avg(filename):
    with open(filename) as f:
        data = [float(line.strip()) for line in f]
    return sum(data) / len(data)

Example output:

from typing import List
import math

class DataProcessor:
    def __init__(self, filename: str):
        self.filename = filename

    def read_file(self) -> List[float]:
        """Read numbers from a file into a list."""
        with open(self.filename) as f:
            return [float(line.strip()) for line in f]

    def clean_data(self, data: List[float]) -> List[float]:
        """Remove negative values and NaN."""
        return [x for x in data if x >= 0 and not math.isnan(x)]

    def calculate_average(self) -> float:
        """Return the mean of cleaned data."""
        data = self.read_file()
        cleaned = self.clean_data(data)
        return sum(cleaned) / len(cleaned)

Explanation: This prompt includes the original code, so the AI can preserve behavior. It also explicitly asks for docstrings, which improves maintainability.

Intermediate Prompts

4. Web Scraper with Retry and Politeness

Use case: You want to collect data from a website, but you need to avoid getting blocked.

Prompt:

Generate a Python script using the requests and BeautifulSoup libraries. The script should fetch a list of quotes from http://quotes.toscrape.com/ and print the text and author of each quote on the first page. Add a ret
ry loop with a maximum of 3 attempts. Use `time.sleep(2)` between attempts to avoid hammering the server. If all attempts fail, print an error message and return `None`.

Example output:
```python
import time
import requests
from bs4 import BeautifulSoup

def fetch_quotes(url, max_attempts=3):
for attempt in range(max_attempts):
try:
response = requests.get(url, timeout=5)
response.raise_for_status()
break
except requests.RequestException:
if attempt == max_attempts - 1:
print(

← All posts

Comments