ChatGPT – For Code Writing



ChatGPT can serve as a versatile companion and assist developers in various coding tasks such as generating code snippets, bug fixing, code optimization, rapid prototyping, and translating code between languages. This chapter will guide you, through practical examples in Python using the OpenAI API, how ChatGPT can enhance your coding experience.

Automated Code Generation Using ChatGPT

We can create code snippets in any programming language effortlessly with ChatGPT. Let’s see an example where we used OpenAI API to generate a python code snippet to check if a given number is an Armstrong number or not −

Example

import openai

# Set your OpenAI API key
openai.api_key = 'your-api-key-goes-here'

# Provide a prompt for code generation
prompt = "Generate Python code to check if the number is an Armstrong number or not."

# Make a request to the OpenAI API for code completion
response = openai.Completion.create(
   engine="gpt-3.5-turbo-instruct",
   prompt=prompt,
   max_tokens=200
)

# Extract and print the generated code from the API response
generated_code = response['choices'][0]['text']
print(generated_code)

Output

The above code snippet will give us the below Python code snippet that we can use to check if the given number is Armstrong number or not.

num = int(input("Enter a number: "))
sum = 0
temp = num

while temp > 0:
   digit = temp % 10
   sum += digit ** 3
   temp //= 10

if num == sum:
   print(num, "is an Armstrong number")
else:
   print(num, "is not an Armstrong number")

Bug Fixing Using ChatGPT

ChatGPT can help us in identifying and fixing bugs in our code. It can also provide insights to make our code error-free. To make it clear, let’s see an example below −

import openai

# Set your OpenAI API key
openai.api_key = 'your-api-key-goes-here'

# Example code with a bug
code_with_bug = "for j in range(5): print(i)"

# Provide a prompt to fix the bug in the code
prompt = f"Fix the bug in the following Python code:\n{code_with_bug}"

# Make a request to the OpenAI API for bug fixing
response = openai.Completion.create(
   engine="gpt-3.5-turbo-instruct",
   prompt=prompt,
   max_tokens=150
)

# Extract and print the fixed code from the API response
fixed_code = response['choices'][0]['text']
print(fixed_code)

After running the above code snippet, ChatGPT will give you the below insight −

The bug in the above code is that the variable used in the loop, "j", is not 
being used at all in the loop body. Instead, the variable "i" is being 
printed, which is not declared or initialized anywhere in the code snippet. 

To fix this bug, we can either replace "i" with "j" in the loop body, or 
change the initial variable in the loop definition from "j" to "i" to ensure 
that the correct variable is being used in the loop. 

Corrected code:

for i in range(5):
   print(i)

Code Optimization Using ChatGPT

We have seen ChatGPT can generate code snippets very quickly and can also identify and fix the bugs in our code. Another crucial part of the development process is code optimization which helps us improve performance and speed of any application.

Example

The following code shows how ChatGPT can help us optimize our code −

import openai

# Set your OpenAI API key
openai.api_key = 'your-api-key-goes-here'

# Example code to optimize
code_to_optimize = "sum_of_squares = sum(i**2 for i in range(1000000))"  

# Provide a prompt to optimize the code
prompt = f"Optimize the following Python code:\n{code_to_optimize}"

# Make a request to the OpenAI API for code optimization
response = openai.Completion.create(
   engine="gpt-3.5-turbo-instruct",
   prompt=prompt,
   max_tokens=200
)

# Extract and print the optimized code from the API response
optimized_code = response['choices'][0]['text']
print(optimized_code)

Output

Here are the suggestions to optimize the above code is given by ChatGPT −

One possible way to optimize this code is to use the built-in function "sum" 
with a list comprehension instead of a generator expression. 
This can be done as follows:

sum_of_squares = sum([i**2 for i in range(1000000)])

Using list comprehension instead of a generator expression can reduce the 
time complexity of this code from O(n) to O(1). This is because list 
comprehension creates a list of all the squared values beforehand, 
while generator expressions calculate each squared value individually
when needed. This makes the computation for summing the squared 
values much faster.

Another optimization technique could be to use the built-in function "pow" 
instead of the exponential operator "**". This can be done as follows:

sum_of_squares = sum(pow(i,2) for i in range(1000000))

The "pow" function is optimized for calculating powers and may
improve the performance of the code.

Rapid Prototyping Using ChatGPT

Rapid prototyping is another crucial step in the development process. It allows developers to quickly test and iterate on ideas. ChatGPT, with its ability to generate code snippets, has become a valuable tool for swift prototyping.

Example

In this example, we'll explore how ChatGPT can assist in creating a Python code snippet for fetching data from a web API and printing the first 3 results.

import openai

# Set your OpenAI API key
openai.api_key = 'your-api-key-goes-here'

# Provide a prompt for rapid prototyping
prompt = "Create a Python code snippet to fetch data from a web API and print the first 3 results."

# Make a request to the OpenAI API for code completion
response = openai.Completion.create(
   engine="gpt-3.5-turbo-instruct",
   prompt=prompt,
   max_tokens=250
)

# Extract and print the prototyped code from the API response
prototyped_code = response['choices'][0]['text']
print(prototyped_code)

Output

Let’s see the response from ChatGPT −

import requests 

# Define the URL of the web API
url = "https://example.com/api"

# Send a GET request and store the response 
response = requests.get(url)

# Convert the JSON response to a Python dictionary 
data = response.json()

# Loop through the first 3 items in the response 
for i in range(3):
   # Print the title and description of each item 
   print("Title:", data["results"][i]["title"])
   print("Description:", data["results"][i]["description"])
# Output: 
# Title: Example Title 1
# Description: This is the first example result.
# Title: Example Title 2
# Description: This is the second example result.
# Title: Example Title 3
# Description: This is the third example result.

Code Translation and Migration Using ChatGPT

One of the common challenges while working on diverse projects is code translation and migration. ChatGPT can streamline this process by generating code translations, allowing developers to adapt code snippets to different languages or frameworks.

Example

In this example, we'll explore how ChatGPT can assist in translating a Python code snippet to JavaScript.

import openai

# Set your OpenAI API key
openai.api_key = 'your-api-key-goes-here'

# Example Python code for translation
original_code = "print('Hello, World!')"

# Provide a prompt to translate the code to JavaScript
prompt = f"Translate the following Python code to JavaScript:\n{original_code}"

# Make a request to the OpenAI API for code translation
response = openai.Completion.create(
   engine="gpt-3.5-turbo-instruct",
   prompt=prompt,
   max_tokens=150
)

# Extract and print the translated code from the API response
translated_code = response['choices'][0]['text']
print(translated_code)

Output

Let’s check out the code translation below −

console.log('Hello, World!');

Conclusion

This chapter showcased how ChatGPT can help you in coding. We learned how to generate codes, fix bugs, optimize code, rapid code prototyping, and even translate code between languages.

Advertisements