```python
"""Utility module for calculating customer-specific price discounts."""
def calculate_discount(price, customer_type):
"""Calculate the final price after applying a discount based on customer type.
Applies a 20% discount for VIP customers, and a 5% discount for regular
customers whose purchase exceeds 100. All other cases return the original
price unchanged.
Parameters:
price (float): The original price of the item before any discount.
customer_type (str): The category of the customer (e.g., 'vip', 'regular').
Returns:
float: The price after the applicable discount has been applied.
"""
# VIP customers receive a flat 20% discount regardless of price
if customer_type == 'vip':
return price * 0.8
# Regular customers qualify for a 5% discount only on purchases over 100
elif customer_type == 'regular' and price > 100:
return price * 0.95
# No discount applies; return the original price
return price
```
Automatically Add Comments to Python Code with AI
Tested prompts for ai add comments to python code compared across 5 leading AI models.
If you have Python code that lacks documentation, AI can scan the logic and insert inline comments, docstrings, and block explanations automatically. This saves hours of manual annotation work, especially when you are inheriting a codebase, preparing code for a team review, or submitting a project that requires documented source files.
The core workflow is simple: paste your Python function or script into an AI prompt, ask it to add comments explaining what each section does, and get back a fully annotated version. The output typically includes inline comments above complex lines, docstrings for functions and classes, and short block comments before logical groupings like loops or conditionals.
This page shows you the exact prompt to use, compares how four leading AI models handle the same Python snippet, and explains when AI-generated comments are reliable versus when you need to review them carefully. Whether you are documenting a data pipeline, a web scraper, or a machine learning script, the approach here gets you to commented code in under a minute.
When to use this
AI comment generation works best when the code itself is already functioning correctly and you need documentation layered on top. It fits solo developers, students submitting assignments, engineers onboarding teammates, and anyone doing a documentation sprint on legacy or inherited Python files.
- You inherited undocumented Python scripts from a previous developer and need to understand and explain them quickly
- You are a student who wrote working code but needs to add comments before submission
- You are preparing a pull request and your team requires docstrings on all public functions
- You are building internal tooling and want a first pass of documentation before a code review
- You are converting a Jupyter notebook into a standalone script and need prose explanations converted to inline comments
When this format breaks down
- Do not use AI-generated comments as a substitute for understanding the code yourself before shipping it to production. If the AI misreads the logic and writes an incorrect comment, that misleading annotation can cause real bugs downstream when other developers follow it.
- Avoid this approach on heavily obfuscated or minified Python, such as compiled or auto-generated files. The AI will produce comments that sound plausible but may not reflect actual intent.
- If your codebase contains proprietary algorithms or sensitive business logic, pasting it into a third-party AI model raises data privacy concerns. Check your organization's policy before using cloud-based models.
- Do not rely on AI comments for security-critical code paths without expert review. AI tends to describe what code does mechanically but may miss subtle security implications like input sanitization gaps or race conditions.
The prompt we tested
You are an expert Python developer and technical writer. Your task is to add clear, helpful comments to the Python code provided below without changing any of the actual code logic, syntax, or formatting.
Follow these instructions carefully:
Add a module-level docstring at the top, PEP 257-compliant docstrings for every function and class (describing purpose, parameters, and return values), and concise inline comments (#) only where the logic is non-obvious. Do not modify, reformat, or refactor the original code—only insert comments and docstrings. Keep comments clear, professional, and free of redundant explanations of trivial operations.
Here is the Python code to comment:
def calculate_discount(price, customer_type):
if customer_type == 'vip':
return price * 0.8
elif customer_type == 'regular' and price > 100:
return price * 0.95
return price
Return the fully commented Python code inside a single code block, preserving the original code exactly as written and adding only comments and docstrings where appropriate.
Model comparison
| Model | Quality | Cost | Latency | Tokens |
|---|---|---|---|---|
| Claude Opus 4.7 | 8 | $0.0295 | 4.5s | 335 / 326 |
| Claude Haiku 4.5 | 9 | $0.0015 | 2.7s | 250 / 241 |
| GPT-5.4 | 8 | $0.0027 | 2.6s | 224 / 145 |
| Gemini 2.5 Pro | 9 | $0.0014 | 6.1s | 236 / 221 |
| Grok 4.1 Fast Reasoning | 8 | $0.0002 | 8.5s | 371 / 192 |
Outputs
```python
"""
Module for calculating discounts based on customer type and purchase price.
This module provides functionality to apply tiered discount rules to customer
purchases, with special pricing for VIP customers and bulk purchases.
"""
def calculate_discount(price, customer_type):
"""
Calculate the discounted price based on customer type and purchase amount.
Args:
price (float): The original price of the item or purchase.
customer_type (str): The customer classification ('vip', 'regular', or other).
Returns:
float: The final price after applying applicable discounts.
"""
# VIP customers receive a 20% discount on all purchases
if customer_type == 'vip':
return price * 0.8
# Regular customers receive a 5% discount on purchases over $100
elif customer_type == 'regular' and price > 100:
return price * 0.95
# No discount applied for other customer types or low-value regular purchases
return price
```
```python
"""Utility functions for applying customer-specific purchase discounts."""
def calculate_discount(price, customer_type):
"""Calculate the discounted price based on customer type and purchase amount.
Args:
price: The original price of the item or order.
customer_type: The category of customer, such as 'vip' or 'regular'.
Returns:
The final price after applying any eligible discount.
"""
if customer_type == 'vip':
return price * 0.8
elif customer_type == 'regular' and price > 100:
# Regular customers receive a smaller discount only on higher-value purchases.
return price * 0.95
return price
```
```python
"""A simple module for calculating customer discounts."""
def calculate_discount(price, customer_type):
"""Calculates a final price after applying a discount based on customer type.
Args:
price (float or int): The original price of the item.
customer_type (str): The type of customer ('vip' or 'regular').
Returns:
float or int: The price after applying the applicable discount. Returns the
original price if no discount conditions are met.
"""
if customer_type == 'vip':
# VIP customers receive a 20% discount regardless of price.
return price * 0.8
elif customer_type == 'regular' and price > 100:
# Regular customers receive a 5% discount for purchases over 100.
return price * 0.95
# No discount is applied for regular customers on purchases of 100 or less.
return price
```
```python
"""Module for calculating customer discounts based on type and price."""
def calculate_discount(price, customer_type):
"""
Calculate the discounted price based on customer type and original price.
Applies discounts as follows:
- VIP customers: 20% off (multiplied by 0.8).
- Regular customers: 5% off (multiplied by 0.95) only if price > 100.
- Otherwise: no discount.
Args:
price (float): The original price of the item.
customer_type (str): The customer type ('vip' or 'regular').
Returns:
float: The final price after discount (or original price if no discount).
"""
if customer_type == 'vip':
return price * 0.8
elif customer_type == 'regular' and price > 100:
return price * 0.95
return price
```
What makes these work
-
01Specify comment depth in your prompt
Asking an AI to 'add comments' without guidance often produces either too many obvious annotations or too few on complex lines. Tell it exactly what you want: inline comments above non-obvious lines, a docstring for every function, and a block comment before each logical section. Specificity in the prompt directly controls output quality.
-
02Send one function at a time for accuracy
When you paste an entire 300-line script, AI models sometimes produce generic comments that could apply to any code. Sending a single function gives the model full context to write comments that are precise to that logic. You can batch several small functions together, but keep the input focused and coherent.
-
03Ask for docstrings in a specific format
Python has three common docstring conventions: Google style, NumPy style, and reStructuredText. If your project already uses one, name it explicitly in your prompt. Saying 'add Google-style docstrings' will get you Args, Returns, and Raises sections formatted correctly for your existing codebase or documentation generator.
-
04Review comments against actual logic
AI reads code statistically and occasionally writes a comment that describes what code looks like it does rather than what it actually does. After generation, read each comment alongside the line it describes. This review pass takes two minutes and catches the rare but consequential case where the comment contradicts the code.
More example scenarios
def clean_sales_data(df):
df = df.dropna(subset=['revenue', 'region'])
df['revenue'] = df['revenue'].astype(float)
df = df[df['revenue'] > 0]
df['region'] = df['region'].str.strip().str.lower()
return df
def clean_sales_data(df):
# Remove rows where revenue or region is missing
df = df.dropna(subset=['revenue', 'region'])
# Ensure revenue is stored as a float for arithmetic operations
df['revenue'] = df['revenue'].astype(float)
# Filter out zero or negative revenue entries
df = df[df['revenue'] > 0]
# Normalize region strings to lowercase with no leading or trailing spaces
df['region'] = df['region'].str.strip().str.lower()
return df
def get_article_links(url):
response = requests.get(url, timeout=10)
soup = BeautifulSoup(response.text, 'html.parser')
links = [a['href'] for a in soup.find_all('a', href=True) if '/article/' in a['href']]
return list(set(links))
def get_article_links(url):
"""Fetch all unique article links from a given webpage URL."""
# Send an HTTP GET request with a 10-second timeout to avoid hanging
response = requests.get(url, timeout=10)
# Parse the raw HTML response into a navigable BeautifulSoup object
soup = BeautifulSoup(response.text, 'html.parser')
# Extract href values from anchor tags that point to article paths
links = [a['href'] for a in soup.find_all('a', href=True) if '/article/' in a['href']]
# Remove duplicate URLs before returning
return list(set(links))
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) model = LogisticRegression(max_iter=1000) model.fit(X_train, y_train)
# Split dataset into 80% training and 20% test sets with a fixed random seed for reproducibility X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Initialize a scaler to standardize features to zero mean and unit variance scaler = StandardScaler() # Fit the scaler on training data and transform it X_train = scaler.fit_transform(X_train) # Apply the same scaling to test data using training statistics only X_test = scaler.transform(X_test) # Define logistic regression model with increased iteration limit to ensure convergence model = LogisticRegression(max_iter=1000) # Train the model on the scaled training features and labels model.fit(X_train, y_train)
def backup_files(src, dest):
if not os.path.exists(dest):
os.makedirs(dest)
for filename in os.listdir(src):
if filename.endswith('.log'):
shutil.copy2(os.path.join(src, filename), dest)
def backup_files(src, dest):
"""Copy all .log files from src directory to dest directory, creating dest if needed."""
# Create the destination directory if it does not already exist
if not os.path.exists(dest):
os.makedirs(dest)
# Iterate over every file in the source directory
for filename in os.listdir(src):
# Only copy files with a .log extension
if filename.endswith('.log'):
# Copy file to destination, preserving metadata like timestamps
shutil.copy2(os.path.join(src, filename), dest)
def compound_interest(principal, rate, n, t):
amount = principal * (1 + rate / n) ** (n * t)
return round(amount - principal, 2)
def compound_interest(principal, rate, n, t):
"""
Calculate compound interest earned over a period.
Args: principal (float): starting amount, rate (float): annual rate as decimal,
n (int): compounding periods per year, t (int): years.
Returns: float: interest earned rounded to 2 decimal places.
"""
# Apply the standard compound interest formula: A = P(1 + r/n)^(nt)
amount = principal * (1 + rate / n) ** (n * t)
# Subtract principal to get only the interest earned, rounded to cents
return round(amount - principal, 2)
Common mistakes to avoid
-
Pasting code without context
If your function uses custom classes or variables defined elsewhere, the AI may misinterpret their purpose and write inaccurate comments. Include a brief note in your prompt explaining what the function does or what the main objects represent. This extra context costs ten seconds and prevents misleading annotations.
-
Accepting every comment without reading
AI can produce confident-sounding comments that are subtly wrong, especially in mathematical functions or state machines. Treating the output as final without a quick review pass introduces incorrect documentation into your codebase, which is often worse than no documentation because it actively misleads future readers.
-
Over-commenting obvious lines
Some AI outputs add comments to every single line including trivially clear ones like variable assignments. This clutters the code and reduces readability. In your prompt, explicitly say 'skip comments on self-explanatory lines' or 'only comment non-obvious logic' to keep the output clean and professional.
-
Ignoring existing comments in the codebase
If you paste code that already has some comments, AI may rewrite or contradict them. Review the output to confirm the AI preserved your original annotations and did not overwrite deliberate notes that contained information the AI could not have inferred, such as known bug workarounds or business rule references.
-
Using AI comments to replace understanding
If you do not understand the code yourself, AI comments give you the illusion of understanding without the substance. This is a problem when you need to debug, extend, or explain the code to others. Use AI comments as a starting point for learning the code, not as a replacement for reading and understanding it.
Related queries
Frequently asked questions
Which AI model is best for adding comments to Python code?
GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro all perform well on Python annotation tasks. GPT-4o tends to write concise and accurate inline comments. Claude often produces more detailed docstrings and explains intent rather than just mechanics. The comparison table on this page shows side-by-side output from four models on the same input so you can judge for yourself.
Can AI add docstrings to all functions in a Python file at once?
Yes, but results are more accurate when you process functions individually or in small groups. You can paste an entire file and ask the AI to add docstrings to every function, and most models will comply. However, longer files increase the chance of generic or slightly off-target comments. For a 500-line file, consider splitting it into logical sections before prompting.
How do I get AI to add Google-style or NumPy-style docstrings specifically?
Name the format explicitly in your prompt. Write something like: 'Add Google-style docstrings to each function, including Args, Returns, and Raises sections where applicable.' The major AI models recognize these conventions and will format output accordingly. If you are using a documentation tool like Sphinx, mention that as well so the model formats for reStructuredText if needed.
Will AI-generated comments slow down my Python code?
No. Python comments are stripped by the interpreter and have zero effect on runtime performance. Docstrings are stored as the __doc__ attribute of objects and consume a negligible amount of memory, but they do not affect execution speed in any meaningful way for typical applications.
Can I use AI to comment code in a VS Code extension or IDE plugin?
Yes. Several VS Code extensions connect to AI models and let you right-click a function to generate or insert comments without leaving the editor. GitHub Copilot, Cursor, and Continue are popular options. They use the same underlying models but integrate directly into your editing workflow so you do not have to copy and paste between a browser and your IDE.
Is it safe to paste proprietary Python code into an AI chatbot to get comments?
It depends on the model and your organization's data handling policy. Consumer-facing products like ChatGPT may use your inputs to improve models unless you opt out or use an enterprise plan with data privacy guarantees. If your code contains trade secrets or regulated data, use a locally hosted model like Code Llama or check whether your AI provider offers a zero-data-retention API tier.
Try it with a real tool
Run this prompt in one of these tools. Affiliate links help keep Gridlyx free.