Get discounts on data, AI, and programming courses. View offers

Vijay Singh Khatri | 08 Jun, 2023

ChatGPT Cheat Sheet for Developers | 40 Best Prompts

ChatGPT has created a huge amount of hype since its release. If you don’t already know, this AI-powered large language model (LLM) can simulate human conversations with impressive ease and accuracy.

While it remains to be seen whether Google Bard will topple ChatGPT from its throne, developers are now turning to ChatGPT on a daily basis. 

Developed by OpenAI, ChatGPT runs on top of the GPT-3.5 and GPT-4 families of language models. And with 100 million users and 1 billion visitors per month, ChatGPT currently receives 10 million requests per day!

Simply provide a descriptive text prompt or description of what you want ChatGPT to do, and you'll get the desired result. It also remembers your previous queries and declines inappropriate requests. 

As a developer, learning how to master ChatGPT can help you to generate code snippets in various languages, learn programming concepts by example, quickly debug code, write test cases, write documents, and gather information.

All of this adds up to huge time savings when writing or debugging code. 

The key to using ChatGPT is the humble text prompt. If these are accurate, precise, and clearly indicate what you want to do, you’ll get the desired results quickly. That’s why we created this ChatGPT cheat sheet for developers.

Whether you’re a coding beginner or a seasoned developer, we’ve added 40 descriptive text prompts to save you time during development. We’ve also taken the time to break down how to create an effective text prompt for ChatGPT. Let’s dive in! 

How Does ChatGPT Work? 

Developed by OpenAI, ChatGPT leverages a deep neural network to respond to user queries. This model uses massive volumes of data to generate responses for a wide range of queries, spanning from science and technology to literature. 

Let’s take a closer look at a high-level overview of how ChatGPT works: 

  • A user inputs a text prompt with the ChatGPT interface, whether that’s a question, a request for information, or a general statement 
  • The AI language model analyzes and interprets the input using machine learning algorithms and responds to user requests by using its trained data 
  • The user receives a response in the form of text
  • The user can input additional text prompts, and the AI language model will analyze these to generate a relevant response
  • This process continues until the user ends the conversation 

How to Write Effective ChatGPT Text Prompts

If you want to generate useful information from ChatGPT, your text prompt has to be effective and descriptive.

Text prompts are what make this chatbot run. Without them, it would not be possible for ChatGPT to respond to your queries. 

More importantly, poorly-written text prompts will often result in irrelevant and incorrect responses from ChatGPT.

Let’s take a look at some guidelines to help you write effective text prompts. 

  • Use Keywords: Add keywords for your topic to help ChatGPT understand the context and what you expect from the response. You could even use keyword research tools to generate keywords for your text prompts. 
  • Be Specific and Concise: Simple, clear, and concise text prompts are essential to getting relevant and correct results. Vague or broad text prompts may result in confusing responses. Also, avoid technical jargon. 
  • Provide Context: Adding context to your query will help ChatGPT generate an accurate response and relevant response. 
  • Use Proper Grammar and Spelling: Changes in spelling or grammar can change the context of a question, so use proper grammar and spelling for text prompts. 
  • Keep it Simple and Engaging: Keep your text prompt simple to allow the AI model to understand it easily. Avoid overly complex words or phrases.
  • Ask Open-Ended Questions: Ask the AI model open-ended questions to enable a variety of responses. Yes or no questions do not produce detailed answers. 
  • Have Fun and Be Creative: Try different text prompts, analyze the responses, and find which text prompts work best to get the most relevant results. 

Let's look at some examples of effective and, importantly, ineffective ChatGPT prompts.

Examples of Effective Text Prompts:

Can you provide me with the salient features of Angular, a front-end development framework?

This is clear, concise, and simple for ChatGPT to understand and respond quickly. 

Can you generate a code snippet in Python for displaying the Fibonacci series of up to 10 natural numbers?

This is specific, relevant, and simple, helping the AI language model to provide the desired response. 

Examples of Ineffective Text Prompts:

Can you generate a code snippet for finding the average from the given numbers?

This prompt does not tell ChatGPT which programming language to use to generate the code snippet. 

Can you help me with the following code snippet?

This prompt does not specify the type of help that ChatGPT should provide for the code. 

ChatGPT Prompts for Code Generation 

1. Can you generate code for [add specific programming task or problem] in [specify programming language or framework]?

Example Prompt: Can you generate code for a function that takes a list of n integers and returns a new list of only even numbers from the input list? I want you to create this function in the Python language. 

2. What is the most efficient or elegant way to generate code for [insert specific programming task or solution] in [insert programming language or framework]?

Example Prompt: What is the most efficient way to write code in JavaScript to find the sum of the list of integers?

3. Is there a library or tool that can assist with generating code for [insert specific programming task or goal] in [insert programming language or framework]?

Example Prompt: Is there any library or tool that can help me generate code for working with dates in Java?

4. Write a [language] function to filter [data structure] based on [condition] with the following inputs: [input variables] and expected output: [output description].

Example Prompt: Write a Python function to filter a list of integers based on whether they are greater than 5, with the following input variables:

Input: list of integers

Expected output: a new list containing only the integers greater than 5.

5. Design a [language] algorithm to solve [problem] using [strategy or technique].

Example Prompt: Design a C++ algorithm to find the maximum element in an array using the divide and conquer strategy.

ChatGPT Prompts for Code Completion

6. Complete the [language] code that [function]: code snippet

Example Prompt: Complete the Python code that takes the list of integers and returns the sum of all elements: 

def sum_list(nums): 

7. Complete the [language] code to convert [data structure] into [output format]: [code snippet].

Example Prompt: Complete the Java code to convert an integer into a string: 

import java.util.*;

public class Example{

8. Finish the [language] implementation of a multithreading solution for [problem]

Example Prompt: Finish the Java implementation of a multithreading solution for a program that calculates the sum of even and odd numbers in a given range. 

import java.util.*;

public class evenodd {

ChatGPT generates the following code: 

import java.util.*;
public class evenodd {
    public static void main(String[] args) throws InterruptedException {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the lower range: ");
        int lower = sc.nextInt();
        System.out.print("Enter the upper range: ");
        int upper = sc.nextInt();

        SumThread evenThread = new SumThread(lower, upper, true);
        SumThread oddThread = new SumThread(lower, upper, false);

        evenThread.start();
        oddThread.start();

        evenThread.join();
        oddThread.join();

        int evenSum = evenThread.getSum();
        int oddSum = oddThread.getSum();

        System.out.println("Sum of even numbers: " + evenSum);
        System.out.println("Sum of odd numbers: " + oddSum);
    }
}

class SumThread extends Thread {
    private int lower;
    private int upper;
    private boolean isEven;
    private int sum;

    public SumThread(int lower, int upper, boolean isEven) {
        this.lower = lower;
        this.upper = upper;
        this.isEven = isEven;
        this.sum = 0;
    }

    public void run() {
        for (int i = lower; i <= upper; i++) {
            if (i % 2 == 0 && isEven) {
                sum += i;
            } else if (i % 2 != 0 && !isEven) {
                sum += i;
            }
        }
    }

    public int getSum() {
        return sum;
    }
}

 

ChatGPT Prompts for Bug Detection

9. Locate any logical errors in the following [language] code snippet: [code snippet]

Example Prompt: Locate any logical errors in the following JavaScript code: 

function calculateSum(nums) {
  let sum = 0;
  for (let i = 1; i < nums.length; i++) {
    if (nums[i] % 2 == 0) {
      sum += nums[i];
    }
    else {
      sum -= nums[i];
    }
  }
  return sum;
}

let nums = [1, 2, 3, 4, 5];
console.log(calculateSum(nums));

10. Find the performance issues in the [language] code: code snippet. 

Example Prompt: Find the performance issues in the Python code: 

def find_max(lst):
    max_value = lst[0]
    for i in range(1, len(lst)):
        if lst[i] > max_value:
            max_value = lst[i]
    return max_value

lst = [5, 10, 3, 8, 12]
print(find_max(lst))

11. Check for potential deadlock issues in the [language] code: code snippet. 

Example Prompt: Check the potential deadlock issues in Java code: 

public class BankAccount {
    private double balance;
    private int accountNumber;
    
    public BankAccount(int accountNumber, double balance) {
        this.accountNumber = accountNumber;
        this.balance = balance;
    }
    
    public synchronized void deposit(double amount) {
        balance += amount;
    }
    
    public synchronized void withdraw(double amount) {
        balance -= amount;
    }
}

public class BankTransaction implements Runnable {
    private BankAccount account1;
    private BankAccount account2;
    
    public BankTransaction(BankAccount account1, BankAccount account2) {
        this.account1 = account1;
        this.account2 = account2;
    }
    
    public void run() {
        synchronized(account1) {
            synchronized(account2) {
                account1.withdraw(100);
                account2.deposit(100);
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account1 = new BankAccount(123, 1000.0);
        BankAccount account2 = new BankAccount(456, 2000.0);
        
        BankTransaction transaction1 = new BankTransaction(account1, account2);
        BankTransaction transaction2 = new BankTransaction(account2, account1);
        
        Thread t1 = new Thread(transaction1);
        Thread t2 = new Thread(transaction2);
        
        t1.start();
        t2.start();
    }
}

12. Analyze the following [language] code and determine potential SQL injection vulnerabilities: [code snippet] 

Example Prompt: Analyze the following PHP code and determine potential SQL injection vulnerabilities:

$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $query);

 

ChatGPT provides the following answer: 

ChatGPT Prompts for Algorithm Development

13. Write a heuristic algorithm to solve a specific problem: [problem description]

Example Prompt: Write a heuristic algorithm to solve a travel salesman problem. 

14. Analyze the following machine learning algorithm to improve its accuracy: [algorithm/pseudocode]. 

Example Prompt: Consider that we have a current algorithm that predicts customers’ sentiments. The text prompt would be: 

Analyze the following machine learning algorithm to improve its accuracy: 

  • Compile a database of client reviews together with the associated emotions (good or negative).
  • Clean up the text and transform it to a numerical representation (such as bag-of-words) to prepare the data.
  • Create training and test sets from the dataset.
  • Utilize the training set to train a Naive Bayes classifier.
  • Use measures like accuracy, precision, recall, and F1 score to assess the classifier's performance on the test set.

15. Create a streaming algorithm to process data in real-time for [a specific purpose].

Example Prompt: Create a streaming algorithm to process data in real-time for the stock market. 

16. Assess the trade-offs of the given algorithm in terms of performance and resource usage: [algorithm or pseudocode].

Example Prompt: Asses the trade-offs of the following algorithm in terms of performance and resource usage: 

  • Compile a database of client reviews together with the associated emotions (good or negative).
  • Clean up the text and transform it to a numerical representation (such as bag-of-words) to prepare the data.
  • Create training and test sets from the dataset.
  • Utilize the training set to train a Naive Bayes classifier.
  • Use measures like accuracy, precision, recall, and F1 score to assess the classifier's performance on the test set.

ChatGPT Prompts for Code Review

17. Review the following [language] code for code smells and suggest improvements: [code snippet].

Example Prompt: Review the following Python code for code smells and suggest improvements: 

def calculate_mean(numbers):
    total = sum(numbers)
    mean = total / len(numbers)
    return mean

def calculate_median(numbers):
    numbers.sort()
    if len(numbers) % 2 == 0:
        mid = len(numbers) / 2
        median = (numbers[mid - 1] + numbers[mid]) / 2
    else:
        mid = len(numbers) // 2
        median = numbers[mid]
    return median

numbers = [1, 2, 3, 4, 5]
mean = calculate_mean(numbers)
median = calculate_median(numbers)

print(f"Mean: {mean}")
print(f"Median: {median}")

18. Review the following [language] code for scalability issues: [code snippet]. 

Example Prompt: Review the following Java code for scalability issues: 

public class MyDatabase {
    private List<String> data;

    public MyDatabase() {
        data = new ArrayList<String>();
    }

    public void insert(String value) {
        data.add(value);
    }

    public String find(String key) {
        for (String value : data) {
            if (value.startsWith(key)) {
                return value;
            }
        }
        return null;
    }
}

19. Evaluate the following [language] code for compatibility with [technology]: [code snippet]. 

Example Prompt: Evaluate the given Java code for compatibility with NetBeans IDE: 

public class MyDatabase {
    private List<String> data;

    public MyDatabase() {
        data = new ArrayList<String>();
    }

    public void insert(String value) {
        data.add(value);
    }

    public String find(String key) {
        for (String value : data) {
            if (value.startsWith(key)) {
                return value;
            }
        }
        return null;
    }
}

20. Evaluate the test coverage of the [language] code: [code snippet]. 

Example Prompt: Evaluate the test coverage of the Python code: 

def calculate_mean(numbers):
    total = sum(numbers)
    mean = total / len(numbers)
    return mean

def calculate_median(numbers):
    numbers.sort()
    if len(numbers) % 2 == 0:
        mid = len(numbers) / 2
        median = (numbers[mid - 1] + numbers[mid]) / 2
    else:
        mid = len(numbers) // 2
        median = numbers[mid]
    return median

numbers = [1, 2, 3, 4, 5]
mean = calculate_mean(numbers)
median = calculate_median(numbers)

assert mean == 3
assert median == 3

ChatGPT Prompts for Natural Language Processing

21. Perform text classification of the following text: [text sample]. 

Example Prompt: Perform text classification of the following text:

"Apple is expected to release a new version of the iPhone next month with improved features and a better camera. The company has been facing tough competition from Samsung and other rivals in the smartphone market, but hopes that the new release will help boost sales."

22. Analyze the sentiment of the following product review: [product review].

Example Prompt: Analyze the sentiment of the following product review:

"I recently purchased the new iPhone, and I'm extremely happy with my purchase! The camera is amazing, and the new features make it so much easier to use. The only downside is the price, but it's worth it for the quality. Overall, I highly recommend this phone to anyone in the market for a new one."

23. List out the key phrases in the social media posts: [social media post]. 

Example Prompt: List out the key phrases in the following social media post: 

“Exciting news everyone! We are thrilled to announce the launch of our brand-new digital marketing platform! 🚀🎉

This platform is the perfect solution for anyone looking to take their online presence to the next level. With powerful tools to help you create and manage your campaigns, you can reach your target audience like never before. 📈

Say goodbye to the hassle of managing multiple platforms and hello to a seamless and intuitive experience. Our platform is designed to help you save time, increase efficiency, and drive results.

Don't wait any longer to take your online marketing to the next level. Try our new platform today and experience the difference for yourself. 💻💪 #digitalmarketing #newproductlaunch #onlinemarketing” 

ChatGPT Prompts for Code Refactoring

24. Suggest the refactoring improvements for the following [language] code: [code snippet]. 

Example Prompt: Suggest the refactoring improvements for the following Python code: 

def calculate_grade(score):
    if score >= 90:
        grade = "A"
    elif score >= 80:
        grade = "B"
    elif score >= 70:
        grade = "C"
    elif score >= 60:
        grade = "D"
    else:
        grade = "F"

    return grade

25. Optimize the following [language] code for lower memory usage: [code snippet]. 

Example Prompt: Optimize the following JavaScript code for lower memory usage: 

function sum(n) {
  let result = 0;
  for (let i = 1; i <= n; i++) {
    result += i;
  }
  return result;
}

console.log(sum(1000000));

26. Refactor the following [language] code to improve its error handling: [code snippet].

Example Prompt: Refactor the following C++ code to improve its error handling: 

#include <iostream>
#include <fstream>

int main() {
  std::string filename = "example.txt";
  std::ifstream file(filename);
  
  if (file) {
    std::cout << "File opened successfully." << std::endl;
  } else {
    std::cout << "Failed to open file." << std::endl;
  }
  
  file.close();
  
  return 0;
}

ChatGPT Prompts for Code Translation

27. Translate the following [language] code for calculating the average of user input numbers into [desired language]: [code snippet]. 

Example Prompt: Translate the following Python code for calculating the average of user input numbers into Java:

numbers = input("Enter numbers separated by spaces: ")
num_list = numbers.split()

try:
    num_list = [float(num) for num in num_list]
except ValueError:
    print("Error: Invalid input")
    exit()

if not num_list:
    print("Error: No numbers provided")
    exit()

average = sum(num_list) / len(num_list)
print("The average is:", average)

ChatGPT Prompts for Requirement Analysis

28. Analyze the following project requirements and suggest the technology stack: [project requirements]. 

Example Prompt: Analyze the following project requirements and suggest the technology stack:

We need to build a web application that allows users to create and share online surveys. The application should allow users to create survey questions, define answer options, and track responses. The application should also allow users to analyze survey results using charts and graphs.

29. Interpret the following project requirements and provide a detailed project plan with milestones and deliverables: [project requirements]. 

Example Prompt: Interpret the following project requirements and provide a detailed project plan with milestones and deliverables:

We need to build a web application that allows users to create and share online surveys. The application should allow users to create survey questions, define answer options, and track responses. The application should also allow users to analyze survey results using charts and graphs.

30. Convert the following project requirements into user stories: [project requirements]. 

Example Prompt: Convert the following project requirements into user stories: 

We need to build a web application that allows users to create and share online surveys. The application should allow users to create survey questions, define answer options, and track responses. The application should also allow users to analyze survey results using charts and graphs. 

ChatGPT Prompts for Networking and Security

31. Create a secure [language] function that performs [specific task] while preventing [security threat or vulnerability]. 

Example Prompt: Write a secure Python function or module that performs password hashing while preventing SQL injection attacks. 

32. Design a secure protocol for [specific use case] for my [app/website]. 

Example Prompt: Design a secure and efficient protocol for secure communication between a client and a server over the Internet.

33. Evaluate the security of the given [language] code when interacting with [external service/API].

Example Prompt: Evaluate the security of the given Python code when interacting with a database:

import psycopg2
conn = psycopg2.connect(
    host="localhost",
    database="mydatabase",
    user="myusername",
    password="mypassword"
)

cur = conn.cursor()
cur.execute("SELECT * FROM mytable")
rows = cur.fetchall()
conn.close()

ChatGPT Prompts for Automated Testing

34. Write a test script for the given [language] code that covers [functional/non-functional] testing. 

Example Prompt: Write a test script for the given Python code that covers functional testing:

numbers = input("Enter numbers separated by spaces: ")
num_list = numbers.split()

try:
    num_list = [float(num) for num in num_list]
except ValueError:
    print("Error: Invalid input")
    exit()

if not num_list:
    print("Error: No numbers provided")
    exit()

average = sum(num_list) / len(num_list)
print("The average is:", average)

35. Design a performance testing strategy for a [web/mobile] app for [resource usage, latency, and throughput]. 

Example Prompt: Design a performance testing strategy for a web app that focuses on latency. 

36. Create a test suite for a [language] library or framework that validates its functionality and stability.

Example Prompt: Create a test suite for a Javascript library or framework that validates its functionality and stability.

37. Create an end-to-end testing strategy for a [mobile/web] app that covers critical user workflows. 

Example Prompt: Create an end-to-end testing strategy for a mobile app that covers critical user workflows.

ChatGPT Prompts for Personalized Development Learning

38. What are the available free resources to learn [programming language/technology]?

Example Prompt: What are the available free resources to learn Python with their official links? 

39. What learning path should I follow to become a proficient [IT job role]? 

Example Prompt: What learning path should I follow to become a proficient DevOps Engineer? 

40. Suggest coding challenges or competitions improve my [programming language/technology] skills. 

Example Prompt: Suggest coding challenges or competitions to improve my front-end development skills. 

Unleash the Power of ChatGPT for Development!

And there you have it, 40 of the most helpful ChatGPT text prompts for developers. We hope you found this ChatGPT Cheat Sheet for developers helpful and interesting!

Whether you’re a beginner to development that’s trying to learn new skills or a seasoned professional that wants to ramp up productivity, these ChatGPT text prompts can help you to save significant amounts of time when writing and debugging code.

While this list is not exhaustive, you should now have a stronger idea of how to use ChatGPT to facilitate the development process while also ensuring response accuracy. 

You should also remember that any code suggestions from ChatGPT may themselves have room for improvement, and they may even contain errors! We hope you feel encouraged to explore this brave new world of AI-assisted development, as with the right prompts and a willingness to learn, ChatGPT can be an amazing tool.

Want to take your AI chatbot skills to the next level? Check out:

The Ultimate Guide to AI Prompt Engineering

People are also reading:

STAY IN LOOP TO BE AT THE TOP

Subscribe to our newsletter

Welcome to the club and Thank you for subscribing!

By Vijay Singh Khatri

With 5+ years of experience across various tech stacks such as C, C++, PHP, Python, SQL, Angular, and AWS, Vijay has a bachelor's degree in computer science and a specialty in SEO and helps a lot of ed-tech giants with their organic marketing. Also, he persists in gaining knowledge of content marketing and SEO tools. He has worked with various analytics tools for over eight years.

View all post by the author

Learn More

Please login to leave comments