• 2 hours
  • Easy

Free online content available in this course.

course.header.alt.is_certifying

Got it!

Last updated on 8/19/24

Write Code Using ChatGPT

Chapter banner

ChatGPT doesn’t just speak human languages. It also speaks programming languages!

If you’re an IT developer, I recommend you get into the habit of using it in your day-to-day work, as it can really save you time. Let’s see how.

Ask ChatGPT to Write Some Sample Code

Imagine that you need to write a program that sorts a list of numbers in a particular order. You have a specific problem, but you’re not sure how to tackle it.

You can ask ChatGPT to help you with a simple prompt, such as “Write a Python program that sorts a list of numbers.”

🧔🏻‍♂️: Write a Python program that sorts a list of numbers.

🤖: Certainly! You can use the built-in  sorted()  function to sort a list of numbers in ascending order. Here's a simple Python program that demonstrates this:

def sort_numbers(numbers):
    sorted_numbers = sorted(numbers)
    return sorted_numbers

# Example usage:

if __name__ == "__main__":

# Input list of numbers

numbers = [4, 2, 7, 1, 9, 3, 5]

# Call the function to sort the numbers

sorted_numbers = sort_numbers(numbers)

# Display the original and sorted lists

print("Original list:", numbers)
print("Sorted list:", sorted_numbers)

This program defines a function  sort_numbers  that takes a list of numbers as input, sorts it using the  sorted()  function, and then returns the sorted list. The example usage section demonstrates how to use this function with a sample list of numbers.

If you want to sort the list in descending order, you can use the `reverse` parameter of the  sorted()  function:

def sort_numbers_descending(numbers):
    sorted_numbers_descending = sorted(numbers, reverse=True)
    return sorted_numbers_descending

# Example usage for descending order:

if __name__ == "__main__":

# Input list of numbers

numbers = [4, 2, 7, 1, 9, 3, 5]

# Call the function to sort the numbers in descending order

sorted_numbers_descending = sort_numbers_descending(numbers)

# Display the original and sorted lists

print("Original list:", numbers)
print("Sorted list (descending):", sorted_numbers_descending)

In this example, the  sort_numbers_descending  function sorts the list in descending order by setting  reverse=True  in the  sorted()  function.

This interaction shows how ChatGPT can help to produce code that solves a particular problem. So, you can focus on higher level tasks, leaving ChatGPT to take care of the rest.

So, why is ChatGPT better in this case?

The response can be customized. I can provide more detail about my specific problem and I’ll get a working solution! 😁

Ask ChatGPT to Write Unit Tests

Writing unit tests is a key skill for any developer, but let’s be honest, it can be pretty tedious!

If something’s tedious, that’s very often a sign that you should get ChatGPT to help with it.

Ask ChatGPT to Generate Tests for Your Code Let’s imagine a scenario where you have a function that calculates the square of a number. You can ask ChatGPT to help you write tests to check this function.

🧔🏻‍♂️: Write a unit test for a Python function that calculates the square of a given number.

🤖: Sure, here's an example of a simple unit test for a Python function that calculates the square of a given number. I'll use the built-in  unittest  module for this example:

import unittest

def calculate_square(number):
    return number ** 2

class TestCalculateSquare(unittest.TestCase):
    def test_positive_number(self):
        self.assertEqual(calculate_square(5), 25)
    def test_negative_number(self):
        self.assertEqual(calculate_square(-3), 9)
    def test_zero(self):
        self.assertEqual(calculate_square(0), 0)

if __name__ == '__main__':
   unittest.main()

In this example, the  calculate_square  function simply returns the square of the input number. The  TestCalculateSquare  class inherits from  unittest.TestCase  , and it contains three test methods:

  1. test_positive_number  : Checks if the square of a positive number (5 in this case) is equal to the expected result (25).

  2. test_negative_number  : Checks if the square of a negative number (-3 in this case) is equal to the expected result (9).

  3. test_zero  : Checks if the square of zero is equal to the expected result (0).

The  self.assertEqual  statements within each test method are used to assert that the calculated result matches the expected result. When you run this script, the  unittest  module will execute these tests and report any failures or errors. If all tests pass, you should see an output indicating that the tests were successful.

So, ChatGPT can help you write robust tests for your code to ensure that your software works as expected.

Use ChatGPT to Refactor Code

Refactoring is a common task in software development. It’s a way of improving the code’s structure and readability without changing its functionality.

Let’s assume you have some code with some nested  for  loops and you want to refactor the code to make it easier to read. You can ask ChatGPT to help.

🧔🏻‍♂️: Refactor this Python code to make it more readable. There are currently too many nested ‘for’ loops.

for i in range(3):
    for j in range(3):
        for k in range(3):
            print(i, j, k) 

🤖:

Screenshot showing the conversation on the ChatGPT website.

By asking ChatGPT to refactor your code, you can improve readability without impacting on its functionality.

Another point to make, you can see here that ChatGPT creates a handy boxed-off area for the code it has produced, and added a "Copy code" button top right of the box. How useful is that!

Ask ChatGPT to Correct Coding Errors

Sometimes, our code doesn’t behave as we expect. It’s at times like these that ChatGPT becomes a valuable tool for spotting and correcting errors.

Let’s assume that you have some code that is supposed to print numbers from 1 to 10, but it only prints up to 9.

🧔🏻‍♂️: Correct this Python code. It’s supposed to print numbers from 1 to 10, but it only prints up to 9.

for i in range(1, 10):
    print(i)

🤖:

The issue with your code is that the  range  function generates numbers up to, but not including, the stop value. So, when you use  range(1, 10)  , it generates numbers from 1 to 9. To include 10, you need to use  range(1, 11)  .

Here's the corrected code:

for i in range(1, 11):
    print(i)

This will print numbers from 1 to 10, inclusive.

By asking ChatGPT to correct your code, you might be in for a surprise. It can sometimes spot quite complicated errors! So, it’s worth considering asking it a question and including the code and the issue. 😉

Ask ChatGPT to Explain an Error Message

Error messages can sometimes be confusing, especially if you’re just starting out. ChatGPT can help you understand these messages and even correct your code based on the error.

For example, let’s say you’d generated the following error in Python:  TypeError: can only concatenate str (not "int") to str .

🧔🏻‍♂️: What does this Python error mean:  TypeError: can only concatenate str (not "int") to str  and how can I correct it?

🤖: The error message  TypeError: can only concatenate str (not 'int') to str  occurs when you try to concatenate (combine) a string with an integer using the  +  operator. In Python, you can concatenate two strings using the  +  operator, but if one of the operands is an integer, you'll get a  TypeError  .

Here's an example of the error:

str_variable = "Hello"
int_variable = 42

result = str_variable + int_variable  
# This line will raise a TypeError

To correct this error, you need to convert the integer to a string before concatenating it with the other string. You can use the  str()  function to convert the integer to a string:

str_variable = "Hello"
int_variable = 42

result = str_variable + str(int_variable)  
# Convert int to str before concatenating

Now,  result  will be a string that contains the concatenated values of  str_variable  and the string representation of  int_variable  .

Alternatively, you can use formatted strings or the  format()  method:

str_variable = "Hello"
int_variable = 42

result = "{}{}".format(str_variable, int_variable)

# or using f-string (Python 3.6 and later)

result = f"{str_variable}{int_variable}"

Both of these methods avoid the need for explicit conversion and handle the concatenation of different types seamlessly.

There are certain scenarios where ChatGPT is more useful, such as solving generic problems, and others where Copilot is a more suitable tool, such as highly specific coding issues.

Let’s Recap

  • ChatGPT doesn’t just write sentences—it can also generate code!

  • You can ask it to write code to tackle common problems.

  • It can automate repetitive tasks, such as writing unit tests.

  • It can refactor your code.

  • It can debug code, explain coding errors, and more.

In the next chapter, we’re going to discover what ChatGPT can do to make it easier for salespeople to do their work.

Example of certificate of achievement
Example of certificate of achievement