Skip to main content
Practice

6

deck

Effective Rules for Prompt Writing

When writing English prompts for AI, the most crucial aspect is clearly specifying the desired output's direction and delivery form using verb choices.

Choosing the correct verbs is particularly impactful in the quality of outcomes from code-related prompts.

Use the Imperative with Base Verbs

  • Example: Debug, Refactor, Implement

Use Specific Verbs to Clarify Actions

  • Instead of make, use optimize, analyze, compare

Comparison of Examples

PromptDescription
I want you to make my program better.Requesting + Abstract verb
Debug and refactor this program.Imperative + Specific verbs

===

Commonly Used Verbs in Prompts

VerbMeaningExample Prompt
implementBuild or create a specific function or featureImplement an API endpoint that handles user authentication.
refactorImprove the structure of existing code without changing its behaviorRefactor the payment module to follow SOLID principles.
optimizeMake something faster or more efficientOptimize the query to reduce latency.
debugFind and fix errors in the codeDebug the error in the user registration flow.
generateAutomatically create code, text, or dataGenerate a script to migrate legacy data.
compareExamine differences or similaritiesCompare the performance of two caching strategies.
analyzeExamine in detail to understand or explainAnalyze logs to detect security vulnerabilities.
writeCreate code, content, or documentation from scratchWrite a script for daily backups with error logging.
identifyDetect or recognize something specificIdentify bottlenecks in the order pipeline.
auditReview code or systems for accuracy, security, or complianceAudit the codebase for security compliance.
documentWrite clear instructions or technical explanationsDocument the new API endpoints for external use.
assessEvaluate or judge based on certain criteriaAssess the scalability of the current infrastructure.

===

Here is a strategy for writing prompts that effectively instruct AI.

1. Presenting Measurable Goals

Instructions with clear metrics are more effective than vague ones.

Write a Python script that generates random numbers.
→ Write a script to generate random numbers. (Vague)
Write a Python script that generates 100 random numbers between 1 and 1000.
→ Write a script that generates 100 random numbers between 1 and 1000. (Clear)

===

2. Specifying Constraints

The more specific the conditions, the higher the quality of the code.

Implement a function to download a webpage's HTML content.
→ Simple implementation instruction
Implement a function in TypeScript to download a webpage's HTML content, avoiding any third-party libraries.
→ Specifies both the language and constraints

===

3. Clear Purpose and Context

Adding context allows the AI to suggest more appropriate code.

Optimize the sorting algorithm.
→ General instruction
Optimize the sorting algorithm to handle a large dataset of customer names efficiently, focusing on minimizing memory usage.
→ Includes purpose and data context

===

4. Using Delimiters

Long prompts can be difficult for information delivery.

Using delimiters increases readability by separating output formats and requirements.

Example of Usage

DelimiterPurpose
#Section separation
"Emphasis on specific words
` / ```Code or output format indication

Here is an example of prompt improvement.

Original Prompt

Write a Python script that processes sales data from an Excel file and outputs a summary report. The summary should print the total sales, average sales per month, and the highest sale to the console.

Long and unstructured instruction

Improved Prompt Structure

# Instruction
Write a Python script that processes sales data from an Excel file.
Print the output to the console in the format below.

# Output:
```log
Total Sales: [total sales value]
Average Sales per Month: [average sales value]
Highest Sale: [highest sale value]
  • Clear section separation with #
  • Output format specified with code block(```)
  • Indication of variable value insertion with brackets ([])

===

5. Few-Shot Prompting

A 'shot' in the prompt context refers to the number of examples provided.

Few-shot prompting is a technique to improve AI's understanding of the problem by providing 2-4 examples, which can increase code accuracy when applied to Unit Tests.

General Prompt

Write a Python function that takes a date string in various formats and returns it in the format "YYYY-MM-DD".

AI Response

from datetime import datetime

def normalize_date(date_str):
return datetime.strptime(date_str, "%Y-%m-%d").strftime("%Y-%m-%d")

If various string formats are inputted, the above code will raise a ValueError because the datetime.strptime(datestr, “%Y-%m-%d”) code only recognizes the “YYYY-MM-DD” format.

# Raises Error
normalize_date("March 21, 2025")
normalize_date("03/21/2025")
normalize_date("21 Mar 2025")

===

Utilizing Few-Shot Prompting

By utilizing a few-shot prompt with four unit test examples as shown below, the AI can generate a more flexible and accurate function based on the various examples.

Write a Python function that takes a date string in various formats and returns it in the format "YYYY-MM-DD".

Here are some examples:

1. Input: "March 21, 2025" → Output: "2025-03-21"
2. Input: "03/21/2025" → Output: "2025-03-21"
3. Input: "2025.03.21" → Output: "2025-03-21"
4. Input: "21 Mar 2025" → Output: "2025-03-21"

AI Response

from dateutil import parser

def normalize_date(date_str):
return parser.parse(date_str).strftime("%Y-%m-%d")
  • Improved to handle various formats
  • Capable of generating code based on test cases

When writing functions based on complex requirements, it's advantageous to apply unit testing with few-shot prompting.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.