Step-By-Step Improving ChatGPT Prompt for Code Generation

ChatGPT has shown impressive capabilities for generating code from natural language prompts. However, crafting effective prompts requires some skill. This article provides tips and examples to help you improve your code generation prompts.

The key is to provide enough context and constraints to guide ChatGPT to produce the desired code.

Specify The Programming Language


Always explicitly state which programming language you want the code in:

Generate a Python function that calculates the area of a circle given the radius. 

This removes ambiguity and allows ChatGPT to focus its model on that language.

Give Examples


Providing code examples helps ChatGPT understand exactly what you’re looking for:

Here is an example of a function in Python that calculates the square of a number:

def square(num):
    return num**2

Can you create a similar function that instead cubes the number?

Giving it something to build off makes it more likely to generate relevant, valid code.

Describe The Goal


Clearly explain what you want the code to accomplish:

Write a Python function named longest_word that takes a sentence as input and returns the longest word in the sentence.

An explicit problem statement gives critical context.

Set Expectations


Tell ChatGPT how to format and constrain its response:

In Python, write a function named print_digits that prints the numbers 0 through 9 each on a separate line. The function should not return anything. Use no more than 5 lines of code.

Setting expectations improves the chances you get clean usable code.

Provide Parameter Types


Specify the data types for function parameters:

Write a function in Python called sum_list that takes a list of integers as a parameter and returns the sum of all integers in the list

This helps ChatGPT write valid, properly typed code.

Ask Follow-Up Questions


If the initial response isn’t quite right, ask clarifying questions:

The code you provided won't handle negative numbers. Can you update the function to sum all numbers, positive or negative?

This allows you to iteratively improve the code.

Request Code Improvements


Ask ChatGPT to optimize working code:

Here is a function for calculating sales tax. How can you update it to be more efficient?

def calculate_tax(amount):
  tax_rate = 0.05
  tax_amount = amount * tax_rate 
  return tax_amount

Leverage its suggestions to improve your code.



Crafting highly effective prompts for code generation takes practice, but following these tips will put you on the right track. Remember to provide context, set expectations, give examples, and ask clarifying questions. With some trial and error, you can learn to produce high quality code using ChatGPT.

Useful Websites: