ChatGPT for Coding: User Guide With Examples

by | ChatGPT

ChatGPT is an advanced AI-powered tool that can transform the way you write code. Developed by OpenAI, ChatGPT accelerates your work by understanding human language prompts and generating code snippets based on your input.

ChatGPT can be used in all aspects of coding such as:

  • Writing code snippets

  • Generating boilerplate code

  • Debugging code

  • Adding documentation

  • Generating unit tests

This article gives you specific examples for each of these tasks and more.

Keep in mind that ChatGPT isn’t meant to replace your work as a developer. Instead, it acts as an additional tool in your toolkit similar to the way IntelliSense, autocomplete, and other developer tools do.

How to Use ChatGPT to Write Code Snippets

If you want a general introduction to the AI tool, start with these articles:

Here, we’ll jump straight into practical examples using it for coding. Let’s start with code snippets.

ChatGPT can help you with code snippets by generating specific examples based on your requests. You can simply ask it to write code for a particular algorithm or a function in your preferred programming language.

It’s important to be as specific and clear as possible in your prompts as the AI model works best with explicit instructions.

For example, if you want to generate a Python function to add two numbers, you could use a prompt like this:

Write a Python function that takes two integers as inputs and returns their sum.

ChatGTP responds by providing a complete function and an example of how to use it. Here is the code snippet we received with the prompt:

chatgpt for coding

How to Use ChatGPT for Code Completion

ChatGPT can also help in completing your partial code snippets. If you’ve started writing a piece of code but are unsure about the correct syntax, the AI tool can provide suggestions based on its understanding of code syntax and structure.

For example, if you started writing a Python function to sort a list but got stuck, you could input your incomplete code and ask ChatGPT for help.

Here is a sample prompt:

Complete this piece of Python code:

def sort_list(my_list):

    # sort the list in ascending order

ChatGPT suggests a complete version with an explanation of the code that it has provided.

output of chatgpt completion of code

How to Use ChatGPT for Boilerplate Code Generation

Boilerplate code refers to sections of code that have to be included in many places with little to no alteration. Some examples include:

  • Setting up a Flask web server in Python

  • Main method declaration in a Java application

  • Initial setup code in an HTML file

The structure of the code tends to stay the same across different projects. Using ChatGPT can speed up the setup process for new projects or features.

The boilerplate code includes the essential structure, any necessary dependencies, and basic functions. This frees you to focus on building your application’s core functionality.

Here is an example prompt:

Provide boilerplate code for setting up a Flask web server in Python.

chatgpt output of boilerplate code

How to Refactor and Improve Existing Code With ChatGPT

The AI tool can be used to enhance and optimize existing code. The tool can propose improvements such as extracting repeated code into functions or simplifying complex boolean expressions.

It can also help identify parts of your code that could be made more efficient. This could be recommending a more suitable data structure or identifying redundant code that can be removed.

When you supply the piece of code to ChatGPT, tell the tool that you want it refactored with a phrase such as “Refactor this Python function: …

How to Debug Your Code With ChatGPT

When you’re having problems with your code, you can provide ChatGPT with the malfunctioning code and a description of the issue. The AI tool will attempt to identify and correct the problem.

For example, suppose you have a Python script that should sort a list in descending order but is generating an error message instead. You can provide the details in a prompt like this:

This Python script should create a list and sort it in descending order:

my_list = [5, 2, 3, 1, 4]

my_list.sort_descending()

It produces this error:

AttributeError: ‘list’ object has no attribute ‘sort_descending’

Please debug the script.

ChatGPT provides an explanation of the error in plainer language. It then provides a sample corrected script, as you can see in this picture:

corrected code from chatgpt

How to Use ChatGPT to Write Unit Tests

ChatGPT can be utilized as a valuable tool in the software testing process. Its ability to understand and generate code makes it particularly suited to helping developers write test cases and unit tests, saving time while ensuring that your software is robust and reliable.

Writing unit tests with ChatGPT can be as simple as providing a description of the behavior you’re testing. Based on your description, ChatGPT will use its training data and knowledge of coding practices to generate an appropriate unit test.

Suppose you have a function in Python that calculates the area of a rectangle and you want to generate a test for it. Here is a sample prompt:

Write a unit test for a Python function called calculate_area that takes two parameters, width and height. The test should verify that the function correctly calculates the area of a rectangle.

ChatGPT provides a detailed unit test. You can also ask for a suite of unit tests for your application.

chatgpt unit test

How to Use ChatGPT to Port from One Language to Another

Code porting means adapting software from one environment to another. This often involves translating code from one programming language to another. Unfortunately, this task can be time-consuming and prone to error.

ChatGPT can be a useful tool during this process. For instance, if you have a Python function that you need to translate into JavaScript, you can provide the function to ChatGPT and ask it to perform the translation.

Here is a sample prompt:

Translate this Python code into Javascript:

def add_two_numbers(a, b):

    return a + b

This picture shows the generated JavaScript function.

chatgpt ported script from python to javascript

Limitations With Code Translation

Later in this article, you’ll learn about some general limitations that ChatGPT has when assisting with coding tasks.

Code translating brings some specific problems. Programming languages have different features, and not all of them translate well with each other.

For example, translating Python’s dynamic typing and list comprehensions to JavaScript could lead to more verbose and less idiomatic code.

Similarly, translating class-based object-oriented features to JavaScript might require significant restructuring.

How to Use ChatGPT to Document Your Code

Many programmers find writing documentation to be the least enjoyable part of the job.

This is where ChatGPT comes to the rescue! It can document code by auto-generating comments and external documentation.

1. Inline Comments

When you provide a piece of code and a description of what it does, ChatGPT can generate comments explaining the purpose of various sections of the code or the overall functionality.

You saw a generated function in a previous section, but it had no inline comments. Here is a sample prompt to fix that:

Add comments to this Python code:

def add_two_numbers(a, b):

    return a + b

The AI tool returns the same script or code with added comments.

chatgpt python code with added comments

2. External Documentation

ChatGPT can also assist in writing external documentation, such as

  • README files

  • Tutorials

  • API documentation

You can provide it with a description of your software or its individual components, and it can generate detailed, human-readable explanations and instructions.

4 Additional Use Cases for ChatGPT

To help get you started with incorporating ChatGPT into your development tasks, here are four specific use cases:

  1. Converting plain text to CSV

  2. Generating filler text

  3. Writing SQL queries

  4. Using Power Automate to Integrate ChatGPT

1. Format Plain Text into CSV Format

ChatGPT can help in transforming plain text data into a CSV format using regular expressions (regex). This can be particularly useful when dealing with raw or unstructured text data that needs to be transformed for data analysis or machine learning tasks.

First, you’ll need to identify the patterns in your plain text data that can be captured using regex. ChatGPT can suggest suitable regex patterns based on the format of your text data.

Once the patterns are identified, you can use ChatGPT to help generate the code needed to apply these regex patterns to your data. This code can match patterns in the text and group data accordingly.

After the regex is applied, ChatGPT can assist in writing the code to format the grouped data into a CSV file. This involves creating a CSV file and writing the extracted data to it.

2. Generate Filler Text

ChatGPT can be an invaluable tool for generating placeholder or filler content. Whether it’s for web design, app development, or document formatting, ChatGPT can provide contextually appropriate, human-like text.

Unlike generic Lorem Ipsum, ChatGPT can generate text on a specific subject, making it ideal for realistic mock-ups or prototypes.

For data testing, ChatGPT can generate structured data according to the specified format. This can be useful for testing database queries or data processing pipelines.

Here is a sample prompt:

Generate test data of five rows of comma-delimited lists of four animals.

Here is what is generated with this prompt:

test data generated by chatgpt

3. Writing SQL Queries

When you use ChatGPT to help with SQL, you can focus more time on higher-level tasks such as designing complex reports.

Our tutorial on using ChatGPT to write SQL queries will get you up to speed!

4. Using Power Automate to Integrate ChatGPT

This video will show you how to integrate ChatGPT with Microsoft Outlook using Power Automate:

Disadvantages of Using ChatGPT for Coding

Now that you’ve learned the extensive ways that the AI tool can help, you may be wondering: can ChatGPT replace programmers?

Despite the impressive capabilities of ChatGPT, it’s not infallible. The code it generates should be reviewed and tested before being used in a production environment.

For example, it may generate code with errors or bugs due to its reliance on pre-existing knowledge and input prompt quality.

Even harder to spot is when the generated code runs successfully but produces wrong results. The accuracy of the generated code depends on the complexity of the requirements and the clarity of the description.

The quality and extent of ChatGPT’s coding capabilities also depend heavily on the training data it has been exposed to. If the model comes across tasks it hasn’t encountered during training, it could generate inadequate or incorrect code.

3 Tips to Mitigate Limitations

Here are our 3 best tips to mitigate these limitations:

  • Be specific about your desired programming language, framework, or library.

  • Familiarize yourself with ChatGPT’s known capabilities and limitations.

  • Combine ChatGPT’s output with your own expertise in coding.

Final Thoughts

You’ve learned how to use ChatGPT to assist in your daily programming tasks. The ability of the AI tool to understand prompts and generate meaningful, context-aware code has made it an excellent assistant for developers.

As AI continues to evolve, you should expect more advanced features and capabilities. Whether you’re a seasoned developer or a novice learning a new programming language, you should take advantage of ChatGPT to boost your productivity and the quality of your code!

author avatar
Sam McKay, CFA
Sam is Enterprise DNA's CEO & Founder. He helps individuals and organizations develop data driven cultures and create enterprise value by delivering business intelligence training and education.

Related Posts