
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.
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! š
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:
test_positive_numberĀ : Checks if the square of a positive number (5 in this case) is equal to the expected result (25).
test_negative_numberĀ : Checks if the square of a negative number (-3 in this case) is equal to the expected result (9).
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.
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)š¤:
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!
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. š
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 TypeErrorTo 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 concatenatingNow, Ā
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.
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.