How to Use ChatGPT for Coding (Examples)

 
One very popular use case for ChatGPT is writing code, and ChatGPT can write code in different programming languages, such R, Python, and Javascript.

Therefore, this tutorial will explain how to use ChatGPT for writing code. It will explore examples in the above-mentioned programming languages.

The key is knowing how to compose a ChatGPT prompt such that ChatGPT understands the kind of problem you are trying to solve, and writes the appropriate solution.

Here is an overview:

Let’s dive into the discussion!

 

ChatGPT Prompt Examples for Writing R Code

Example 1

In this first R example, we will ask ChatGPT to write R code to create a density plot.

Prompt: “Write R code for creating a density plot. I want the plot to display the data of three different categories.”

Response:

Note: The ChatGPT output was quite long, so for that reason, I show only the code that was provided by ChatGPT.

# Load the ggplot2 package
library(ggplot2)
 
# Create sample data for three categories
set.seed(123)
data <- data.frame(
  category = rep(c("Category A", "Category B", "Category C"), each = 100),
  value = c(rnorm(100, mean = 10, sd = 2),
            rnorm(100, mean = 15, sd = 3),
            rnorm(100, mean = 8, sd = 1))
)
 
# Create a density plot using ggplot2
density_plot <- ggplot(data, aes(x = value, fill = category)) +
  geom_density(alpha = 0.5) +
  theme_minimal() +
  labs(title = "Density Plot of Three Categories",
       x = "Value",
       y = "Density") +
  scale_fill_discrete(name = "Category")
 
# Display the density plot
print(density_plot)

 

density plot created by chatgpt

 
ChatGPT’s response to the prompt was definitely good. It created the random data that it used to build the density plot without it being given a dataset.

In R, there are different libraries for creating density plots. However, ChatGPT defaulted to the ggplot2 package, likely because it is the most popular visualization library in R programming.

Example 2

Next, we will tell ChatGPT to create a bar plot with a line plot overlay.

Prompt: “Can you write R code for creating a bar plot with a line plot overlay?”

Response:

# Load the necessary package
library(ggplot2)
 
# Create sample data
data <- data.frame(
  category = c("A", "B", "C", "D", "E"),
  values = c(15, 25, 10, 30, 20),
  line_values = c(5, 15, 7, 20, 12)
)
 
# Create a bar plot with ggplot2
bar_plot <- ggplot(data, aes(x = category, y = values)) +
  geom_bar(stat = "identity", fill = "blue", alpha = 0.6) +
  ylab("Values") +
  ggtitle("Bar Plot with Line Overlay")
 
# Add a line plot overlay
bar_plot_with_line <- bar_plot +
  geom_line(aes(y = line_values, group = 1), color = "red", size = 1) +
  geom_point(aes(y = line_values), color = "red", size = 3)
 
# Display the plot
print(bar_plot_with_line)

 

bar plot with line plot overlay generated by chatgpt

 
Again, ChatGPT did a good job generating the graph in the desired format. Once again, it used the ggplot2 package to generate the graph.

You would notice that we did not have to include much details in the prompts passed to ChatGPT in both examples; yet, ChatGPT understood what was asked of it and gave appropriate responses.

We can also ask ChatGPT to create other kinds of graphs as well, such as histograms, heatmaps, and treemaps.

The use of ChatGPT in R certainly goes beyond writing code for creating graphs. There are still many other solutions ChatGPT can write in the R programming language.
 

ChatGPT Prompt Examples for Writing Python Code

Here, we will take some inspiration from LeetCode and ask ChatGPT to write code to solve different problems in Python.

Example 1

We will prompt ChatGPT to write Python code to check if a number or a string is a palindrome.

Prompt: “Write code to check if a number or a string is a palindrome in Python.”

Response:

def is_palindrome(input):
    # Convert input to string if it's a number
    if isinstance(input, int):
        input = str(input)
    elif not isinstance(input, str):
        raise ValueError("Input must be a number or a string")
 
    # Remove non-alphanumeric characters and convert to lowercase
    clean_input = ''.join(char.lower() for char in input if char.isalnum())
 
    # Check if the cleaned input is equal to its reverse
    return clean_input == clean_input[::-1]
 
# Test cases
print(is_palindrome(121))        # True
print(is_palindrome("racecar"))  # True
print(is_palindrome("hello"))    # False

I ran the code in my Python IDE and it worked as expected. I ran different iterations, and I got the expected output each time.

Let’s see another example!

Example 2

In this example, we will tell ChatGPT to write Python code to find the first and the last position of an element in a sorted array.

Prompt: “Can you write Python code to find the first and last position of element in a sorted array?”

Response:

def find_first_position(arr, target):
    left, right = 0, len(arr) - 1
    result = -1
 
    while left <= right:
        mid = left + (right - left) // 2
 
        if arr[mid] == target:
            result = mid
            right = mid - 1
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
 
    return result
 
def find_last_position(arr, target):
    left, right = 0, len(arr) - 1
    result = -1
 
    while left <= right:
        mid = left + (right - left) // 2
 
        if arr[mid] == target:
            result = mid
            left = mid + 1
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
 
    return result
 
def find_first_and_last_position(arr, target):
    first_position = find_first_position(arr, target)
    last_position = find_last_position(arr, target)
    return first_position, last_position
 
# Example usage
sorted_array = [1, 2, 2, 2, 3, 4, 4, 5, 5, 6]
element_to_find = 2
first_position, last_position = find_first_and_last_position(sorted_array, element_to_find)
print("First position:", first_position)
print("Last position:", last_position)

Again, I ran multiple iterations, and each time I got the correct answer.

Let’s see a third example!

Example 3

In this last example, we will ask ChatGPT to write Python code to construct a sentence from a dictionary of string words.

Prompt: “Given a string s and a dictionary of strings wordDict, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.

Write Python code to solve the above problem.”

Response:

def word_break(s, wordDict):
    def backtrack(start):
        if start == len(s):
            return [[]]
 
        if start in memo:
            return memo[start]
 
        sentences = []
        for end in range(start + 1, len(s) + 1):
            word = s[start:end]
            if word in wordDict:
                next_sentences = backtrack(end)
                for next_sentence in next_sentences:
                    sentences.append([word] + next_sentence)
 
        memo[start] = sentences
        return sentences
 
    memo = {}
    sentences = backtrack(0)
    result = [' '.join(words) for words in sentences]
    return result
 
# Example usage
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
print(word_break(s, wordDict))

Once again, ChatGPT produced valid Python code to solve a problem. These are only a few examples of asking ChatGPT to write Python-based solutions to problems. There are many other tasks in Python that ChatGPT can help with.
 

ChatGPT Prompt Examples for Writing Javascript Code

Javascript is a popular programming language used mostly in web development, and like other programming languages, ChatGPT can also write valid Javascript code. Let’s see a couple of examples.

Example 1

Here, we will ask ChatGPT to write Javascript code to append to a list of string values.

Prompt: “Help me write javascript code to append to a list of string values.”

Response:

// Create an array to store string values
var stringList = ["Value 1", "Value 2", "Value 3"];
 
// Function to append a value to the list
function appendToList(value) {
  stringList.push(value); // Push the new value to the end of the array
}
 
// Call the function to append a new value
appendToList("Value 4");
 
// Print the updated array
console.log(stringList);

I ran the code in Visual Studio Code, and it gave the desired result.

Let’s see a second example!

Example 2

In this example, we will prompt ChatGPT to write Javascript code to multiply all the elements in an array by 2 and return the largest number.

Prompt: “Can you write javascript code to multiply all the elements in an array by 2 and return the largest number?”

Response

function multiplyAndFindLargest(arr) {
    if (arr.length === 0) {
        return undefined; // Return undefined for empty arrays
    }
 
    const multipliedArray = arr.map(element => element * 2);
    const largestNumber = Math.max(...multipliedArray);
 
    return largestNumber;
}
 
const inputArray = [3, 7, 2, 8, 5];
const result = multiplyAndFindLargest(inputArray);
console.log("Largest number after multiplication:", result);

Again, ChatGPT produced valid javascript code. This shows that developers can leverage the power of ChatGPT in their projects.

Nevertheless, regardless of how good ChatGPT’s responses may be, it is advised to always run and test the code it generates, especially if you want to use that code in production. This is because ChatGPT sometimes generates incorrect or inaccurate results. So, use with caution!

 

Video, Further Resources & Summary

Do you need more explanations on how to use ChatGPT to write code? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

In the video, we explain how to use ChatGPT to write code.

 

The YouTube video will be added soon.

 

Furthermore, you could have a look at some of the other interesting AI-based tutorials on Statistics Globe:

This post has shown how to use ChatGPT to write code. Because of its ability to write code, ChatGPT has become very popular among data analysts, data scientists, software engineers, and web developers.

ChatGPT can also debug written code, as it can read and decipher errors in code chunks. These abilities make ChatGPT a go-to tool for finding solutions to technical problems.

I hope you enjoyed reading this tutorial! In case you have further questions, you may leave a comment below.

 

R & Python Expert Ifeanyi Idiaye

This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top