Large language models (LLMs) have quickly gained popularity since OpenAI released ChatGPT for public access. Since then, people have used ChatGPT for fun, creative, and useful purposes. If you’ve dreamed about using ChatGPT as your Python coding mentor, then keep on reading.
Using ChatGPT as your mentor doesn’t mean that you should try to build a software solution without knowing anything about programming. Instead, you’ll focus on using ChatGPT as a learning tool. It probably can’t replace you as a programmer, but it can help you to improve your code and learn in the process.
In this tutorial, you’ll learn how to:
- Set up ChatGPT for use
- Debug your code using ChatGPT
- Improve your code style and code quality
- Pair program with ChatGPT
- Explore alternative implementations of a code snippet
- Get answers to your programming questions
You’ll also get to see examples of how ChatGPT can produce incorrect and irrelevant solutions, and you’ll learn how you can improve its responses by working on better prompts. In the downloadable materials, you get access to all the code snippets in the tutorial, as well as all the prompts that you’ll use to interact with ChatGPT:
Free Bonus: Click here to download the free sample code and engineered prompts that show you how to boost your Python programming skills with the help of ChatGPT.
Set Up Your ChatGPT Coding Mentor
To access ChatGPT, you only need to create an account with OpenAI. When you first head to chat.openai.com, then you’ll be prompted to either sign in or sign up:
If you’ve already played with ChatGPT before and have an active account, then sign in and skip to the next section. Otherwise, continue reading for a quick walk-through on signing up for the service.
If you don’t have an account with OpenAI yet, then click on Sign up. You’ll be redirected to a page that allows you to sign up using your Google or Microsoft account or a personal email address:
If you choose to sign up using your email address, then you’ll need to enter a password next. Choose a strong password and complete the sign-up process.
You’ll then be redirected to the main page of ChatGPT, where you’ll get to interact with the large language model through a conversational interface where you enter questions, and the chat provides answers:
In the future, you can navigate to chat.openai.com
to directly access this page since you’ve completed the sign-up process. Every so often, after your browser session expires, you’ll have to log in again.
Beware of Incorrect and Irrelevant Information
Now that you’ve signed up for ChatGPT, you probably want to give it a spin! But before you hit the throttle, it’s important to know what kinds of issues you might run into. While large language models offer several new possibilities for enhancing your studies, you need to remember the potentially negative effects of using ChatGPT as your coding mentor:
- Overreliance: Leaning too heavily on ChatGPT for answers can hinder your own learning. You build brain paths by thinking, struggling, checking your understanding, and memorizing information.
- Accuracy: ChatGPT’s responses may often be inaccurate or irrelevant. You need to fact-check all of its answers! Otherwise, you might learn wrong concepts and bad practices.
In this section and throughout the tutorial, you’ll encounter a few examples of incorrect and irrelevant answers. Hopefully, these examples will help you keep in mind that even if ChatGPT’s responses seem logical at first sight, they’re not always correct. Sometimes the errors in a response are so subtle that you’ll spot them only if you’re an expert programmer.
Note: For a fascinating case study on ChatGPT’s capabilities and limitations, check out The Real Python Podcast Episode 174: Considering ChatGPT’s Technical Review of a Programming Book with Al Sweigart.
In a classic workflow with ChatGPT, you ask a question in the chat interface, and the underlying language model, GPT-3.5, will create a reply that you’ll see pop up as a chat response. ChatGPT will even format the replies in useful ways. For example, go ahead and ask the chat to generate some useful Python learning material for you:
You: Please show me a table with a cheat sheet of Python’s syntax.
When you ask ChatGPT for a table, then it’ll create Markdown that the chat interface knows to display beautifully. As for the content of that cheat sheet, it’ll pick some of Python’s syntax, and the results might be correct and relevant:
The table that you’ll receive as output will most likely be different. It could be quite similar, but it doesn’t have to be. The LLM behind ChatGPT will always create a new response, predicting the most likely next piece of information based on its training. But the output isn’t deterministic, and it’s often even incorrect.
Note: You can look at different responses by clicking the Regenerate response button. Clicking the button will generate a new response based on your prompt. You’ll notice that the response will be different from the previous one you received.
You can then switch between the different results by using the small arrow keys (<
and >
) that pop up next to the top of the answer.
In this case, you got a list that contains correct information about Python, but is this really a complete overview of Python’s syntax? ChatGPT kicked things off with the print()
and input()
functions, assembled a selection of important keywords, and provided some common and some rather uncommon operators:
Syntax | Description |
---|---|
print() |
Displays output to the console |
input() |
Prompts user for input |
if |
Used for conditional statements |
else |
Used in conjunction with if for alternative conditional statements |
elif |
Used in conjunction with if for additional conditional statements |
while |
Used for loops that repeat while a certain condition is met |
for |
Used for loops that iterate through a sequence of elements |
def |
Used for defining functions |
return |
Used in a function to return a value or values |
class |
Used for defining classes |
import |
Used for importing modules or libraries |
try |
Used for exception handling |
except |
Used in conjunction with try to handle exceptions |
finally |
Used in conjunction with try to execute code regardless of exception |
raise |
Used to raise an exception manually |
assert |
Used for debugging and testing assertions |
in |
Used to check if an element is in a sequence |
not |
Used for negation |
and |
Used for logical AND |
or |
Used for logical OR |
is |
Used for identity testing |
== |
Used for equality testing |
!= |
Used for inequality testing |
> |
Used for greater than testing |
< |
Used for less than testing |
>= |
Used for greater than or equal to testing |
<= |
Used for less than or equal to testing |
+= |
Used for incrementing values |
-= |
Used for decrementing values |
*= |
Used for multiplication |
/= |
Used for division |
%= |
Used for modulo operation |
**= |
Used for exponentiation |
While this could represent a useful cheat sheet in some situations, it’s certainly not complete, and it doesn’t say much about many aspects of Python’s syntax, such as indentation, string literals, and comments. The table doesn’t even show you the most relevant items. You should always be aware that ChatGPT-generated content might not be complete or even entirely relevant.
At its core, the GPT-3.5 language model that powers ChatGPT only predicts a probable next piece of information given the previous input. It does this quite well, but that doesn’t mean that its prediction will be correct or relevant. If you check out the list that it produced, then you may notice that it eventually started adding lesser-used augmented assignment operators.
Why did it add them? If you look through the table from top to bottom, you’ll see that a lot of the items can logically follow each other. For a model that predicts the next token based on the probability of its following the previous token, this makes sense.
However, that doesn’t mean that it’s a good selection. It’s doubtful that any serious Python learning resource would make exactly this list when handing a Python syntax cheat sheet to their students. But ChatGPT does—or at least it did in this one specific example. What output did it create in your case?
Note: You can click on the copy icon (📋) at the top right of the response to copy the ChatGPT output to your clipboard. For example, in this case, it’ll give you the raw Markdown of the cheat sheet table. This is a quick and effective way to continue working with the output outside of the chat interface—for example, in your code editor.
As you’ve seen in this section, ChatGPT is a powerful text-completion tool that can give you a lot of information quickly. It can even help you with formatting the information in helpful ways. However, if you ask questions without much consideration and context, then it’s likely that you’ll get incorrect or irrelevant information. That’s why it’s important to learn how to better wield this tool.
Improve Your Results With Prompt Engineering
You can think of a large language model like GPT-3.5 as a very efficient text-completion algorithm. The model takes the whole text that you provide into account and then selects word tokens based on their likelihood of following the existing text.
As such, the model doesn’t have any understanding of the text you provide—at least not in a way that humans think about understanding. Keeping that in mind will help you decipher why some of the results that you’ll receive will be useful, others might be completely off topic, and others might sound relevant, but will be completely made up.
Finding ways to get better results from an LLM is quickly becoming its own discipline that’s called prompt engineering. It focuses on tweaking how you design the text prompts to get the answers that you’re looking for.
While you won’t focus much on prompt engineering techniques in this tutorial, it’s an important topic to read more about if you’re hitting a wall when using ChatGPT as your Python coding mentor. Knowing some fundamental prompting approaches can help you get much better results.
Note: For a deep dive into prompt engineering, check out Prompt Engineering: A Practical Example, where you’ll work through a real-world task step by step to improve the output that you receive from the LLM.
The main ideas to keep in mind while you write your prompts are:
- Specificity: Be clear and specific with your instructions.
- Clear tasks or questions will usually get better responses.
- Longer, more detailed prompts often produce better results.
- Delimiters can help the model separate conceptual sections of your prompt. For example, you can surround Python code with triple backticks (```).
- Context: Give ample context on what you’re trying to achieve and how.
- Role prompting can help you give initial context on how the model should respond to future prompts.
- Few-shot prompting means that you’re adding examples of your expected output to your prompt, which provides context on what kind of response the model should produce.
- Reasoning: Instruct the model to build complex answers incrementally instead of pushing for immediate answers.
- Spelling out the necessary steps for completing the task helps the model correctly do tasks that would otherwise produce incorrect results.
- Even without spelling out the steps yourself, you can often improve the results by adding a sentence that asks the model to tackle the challenge step by step.
- When asking the model to assess whether a provided input is correct, ask the model to build its own solution first before deciding.
To put some of these concepts into practice, you can expand the initial prompt about your Python cheat sheet. Add a role prompt, write your request in more detail, use delimiters, and give an example.
Note: For the rest of this tutorial, you’ll see the prompts and responses from ChatGPT interactions in quote blocks instead of screenshots. The text isn’t edited, except for splitting up overly long lines of code and adding highlights for readability. This presentation is meant to improve the accessibility of the tutorial content and make it possible for you to read the prompts and output on smaller devices.
A slightly better-engineered conversation about the topic of generating a Python syntax cheat sheet could look like this:
You: You are an expert Python developer with years of experience writing Python code and teaching Python to other programmers. You have vast experience mentoring people who are learning Python. I want you to be my mentor while I learn Python myself. If you understood, respond with the word “Ok”.
ChatGPT: Ok, I understand. I’d be happy to help mentor you as you learn Python!
You: I’d want to have a concise cheat sheet reference of Python’s syntax that I can print out on a single page of paper.
Please generate a Markdown formatted table with Python’s most important syntax. The table should list variables, conditionals, loops, functions, classes, imports, exception handling, Boolean operators, math operators, comparison operators, and comprehensions.
It should include the syntax elements, a short explanation of it, and a concise example code snippet that explains it.
For example, here’s how the list could begin:
Markdown TextCopied!| Syntax | Example | Description | | --- | --- | --- | | Comments | `# Comment` | Notes or explanations in the code that are not executed by the interpreter |
Please continue this list and make sure to show the most important syntax elements. You can mix HTML into the Markdown to improve the presentation.
ChatGPT: Sure, here’s a cheat sheet with some of the most important syntax in Python:
Syntax Example Description Variables x = 5
Assign a value to a variable Conditionals if x == 5:
print("x is 5")
Execute code only if a condition is met Loops for i in range(5):
print(i)
Execute code repeatedly Functions def my_func(x, y):
return x + y
Reusable block of code that performs a specific task Classes class MyClass:
def __init__(self, x):
self.x = x
def my_method(self):
print(self.x)
Blueprint for creating objects with specific attributes and methods Imports import math
print(math.sqrt(4))
Use code from another module or package Exception handling try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Handle errors that might occur during program execution Boolean operators and
,or
,not
Operators that operate on boolean values Math operators +
,-
,*
,/
,//
,%
,**
Operators that perform mathematical operations Comparison operators ==
,!=
,<
,>
,<=
,>=
Operators that compare values Comprehensions [i**2 for i in range(5)]
Concise syntax for creating lists, dictionaries, and sets This is not an exhaustive list, but it covers the most important syntax elements in Python.
The response that you receive when crafting a prompt with more detailed context is significantly more useful than the initial result that was based on a single short question.
Note: In the rest of the tutorial, you’ll see naive prompts that you might quickly type into the chat interface to get reasonably good responses. None of the following examples apply any intentional prompt engineering techniques.
You’ll see how asking normal questions can often be enough, but you’ll also see how using prompts without much context or consideration may lead to unexpected and incorrect results.
ChatGPT can be a good tool for learning Python even without too much prompt engineering. However, you can improve your results significantly when you put some more consideration into how you write the prompts. More context will give you more accurate responses.
For the rest of the tutorial, you can attempt to improve the responses by applying the fundamental prompt engineering techniques that you learned about in this section.
Debug Your Code With ChatGPT’s Help
Running into errors is a normal and expected part of programming. Error messages are there to help you figure out what went wrong and give you pointers on fixing the issue at hand.
If you don’t know what to do with the traceback message, then you can often find good suggestions through a web search. However, it might be hard to identify what link is really relevant to your specific error, especially if you haven’t had a lot of experience running into that error.
ChatGPT adds a new option to the table. When you encounter an error in your program, then you can copy both your code and the traceback into the chat interface and ask your ChatGPT coding mentor what to do.
For example, say you’re drafting a script in your Python REPL where you want to collect user input and perform a calculation with it. But you run into an exception, specifically a TypeError
:
>>> current_age = input("Enter your current age: ")
Enter your current age: 36
>>> print("Next year you'll be:", current_age + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
If you don’t know how to interpret this traceback message, then you can just copy everything and send it as a message to ChatGPT. Your Python coding mentor ChatGPT will give you a thorough answer that identifies the issue in the code and explains why it’s happening in clear and concise language. It’ll even give you a fixed code example that addresses the bug that you ran into:
You:
PythonCopied!>>> current_age = input("Enter your current age: ") Enter your current age: 36 >>> print("Next year you'll be:", current_age + 1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str
ChatGPT: The error message you’re seeing is because
current_age
is being treated as a string, but you’re trying to add an integer value to it. To fix this, you can convertcurrent_age
to an integer using theint()
function before doing the addition. Here’s the corrected code:PythonCopied!current_age = input("Enter your current age: ") next_year_age = int(current_age) + 1 print("Next year you'll be:", next_year_age)
This will first prompt the user to enter their age, and then convert the input to an integer using
int()
. Then it adds 1 to the integer value, and finally prints the result as part of a string usingprint()
.
The response that you received from ChatGPT is solid help for the error that you bumped into. The advice on how to read Python input as integers comes close to what a coding mentor might have given to you in person—if they’re a friendly person, that is!
Note: A knowledgeable mentor might have offered you a slightly different solution that improves on the one shown above by converting the user input to an integer before assigning it to current_age
:
current_age = int(input("Enter your current age: "))
print("Next year you'll be:", current_age + 1)
With this solution, you improve the type safety of your code by making sure that current_age
will be an integer throughout your program.
The LLM behind ChatGPT doesn’t know anything about you. It doesn’t even know anything in the way that humans think about knowledge and reasoning. Still, it was able to immediately string together tokens that make sense, solve your error, and give you personalized help for the issue in your code.
Now you may say that Python already knew what was wrong in this code snippet and told you about it using concise language in its error message. But ChatGPT can do more than explain traceback messages in the context of your code. It can also point out syntax errors—mistakes that come from writing invalid Python code that Python’s parser can’t understand.
Maybe you want to use Python as your calculator, and you attempt to divide a number by another one:
>>> 3 : 4
File "<input>", line 1
3 : 4
^
SyntaxError: illegal target for annotation
Hmm … what’s the invalid syntax here? Are you not remembering your fundamental math operations correctly? Time to ask ChatGPT what went wrong in this division. Go ahead and paste all the content of the code block above into the ChatGPT interface, including the error message. You’ll get a helpful explanation as an answer:
ChatGPT: The error message you received indicates that you tried to use an annotation syntax in an invalid way. In Python, the colon (
:
) is used in several contexts, such as defining function or class signatures, creating slices of a sequence, or creating a dictionary.However, in your code, you are using a colon between two integers, which is not a valid syntax in Python. If you want to express a ratio or fraction between two numbers, you can use the division operator (
/
) instead. For example:PythonCopied!ratio = 3 / 4 print(ratio) # Output: 0.75
This will divide the integer
3
by the integer4
and return a floating-point number representing the quotient. You can then store this value in a variable or use it directly in your code.
Again, your ChatGPT coding mentor identifies the issue in your code, shows you how to fix it, and adds a concise explanation as the cherry on top. Using ChatGPT to debug a Python SyntaxError
also works with more complicated code than the one shown above.
If you aren’t receiving a result that seems relevant to your question, then you can add more context to the error message that you’re posting. In this example, you could add a sentence that clarifies that you’re trying to do division, such as I’m trying to divide two numbers and I get this error.
Like you learned before, you’ll always need to check the answers that you receive for accuracy. ChatGPT will often hallucinate an incorrect answer to your input. For example, try to run the following incorrect import
statement and its error message as a prompt:
>>> from collections import chainmap
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'chainmap' from 'collections'
⮑ (/Users/martin/.pyenv/versions/3.11.0/lib/python3.11/collections/__init__.py)
Python’s collections
module has a similar name but with different capitalization, ChainMap
. The solution to this ImportError
would be to fix the capitalization of the name that you’re importing. That’s a small and straightforward fix, but ChatGPT goes down another route:
ChatGPT: The error message suggests that there is a problem with importing the
chainmap
function from thecollections
module. Thechainmap
function is available in thecollections
module starting from Python 3.3.If you are using Python 3.3 or later and still see this error message, it is possible that there is an issue with your Python installation. Try updating or reinstalling Python.
If you are using an earlier version of Python that does not support
chainmap
, you can use an alternative approach, such as creating a dictionary that combines the values from multiple dictionaries, like so:PythonCopied!dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} combined_dict = dict(dict1, **dict2)
This creates a new dictionary
combined_dict
that contains all the key-value pairs fromdict1
anddict2
. If a key exists in both dictionaries, the value fromdict2
will overwrite the value fromdict1
.
ChatGPT doesn’t suggest changing the capitalization of chainmap
to ChainMap
. It correctly reasons that a name called ChainMap has been present in collections
since Python 3.3. However, it goes on to suggest that you may have an issue with your Python installation if you’re getting this error on Python 3.3 or newer.
It then proceeds to send you on a wild-goose chase of reinstalling Python or combining two dictionaries into one, which doesn’t even reproduce the functionality of ChainMap
. While you can definitely learn something from following these suggestions, these aren’t good suggestions from your token-predicting coding mentor, ChatGPT.
Note: Can you get ChatGPT to give you the correct suggestion with some of the prompt engineering techniques that you studied earlier? Try to give more context, ask it to reason step by step, or ask it to list all the available names in collections
. Then ask your question again.
ChatGPT may give you a suggestion that’s spot-on, or it may lead you astray to far-off shores. When you’re using ChatGPT as your Python coding mentor, then you always need to stay aware of the reality that all the LLM behind the interface does is predict the next token based on probabilities. It may sound convincing, but it can still be completely wrong.
With suggestions for a SyntaxError
, you saw that ChatGPT can give you explanations and solutions for an issue where Python knows that something went wrong but can’t tell you much about what went wrong.
But ChatGPT can go beyond that, helping you with errors in your code where Python doesn’t even know that something is wrong. ChatGPT can help you identify logical errors in your code. Code with logical errors typically runs without problems but doesn’t produce the expected output. It can be hard to find and fix these types of errors.
Assume that you’re practicing for a Python coding interview. You’re attempting to implement a function that tackles the FizzBuzz challenge, where you return "fizz"
for numbers divisible by three, "buzz"
for those divisible by five, and "fizz buzz"
for those divisible by both three and five. You wrote a script that runs and seems to work:
# fizzbuzz.py
def fizzbuzz(number):
if number % 3 == 0:
return "fizz"
elif number % 5 == 0:
return "buzz"
elif number % 15 == 0:
return "fizz buzz"
else:
return number
This may look pretty good, but if you’re calling fizzbuzz()
with some example inputs, then you’ll notice that you’re not consistently getting the output that you expect:
>>> fizzbuzz(3)
"fizz"
>>> fizzbuzz(5)
"buzz"
>>> fizzbuzz(15)
"fizz"
Why doesn’t fizzbuzz(15)
return the expected string "fizz buzz"
? Go ahead and paste the code example into a conversation with ChatGPT and see what the language model comes up with:
ChatGPT: The
fizzbuzz
function takes an input number and returns “fizz” if the number is divisible by 3, “buzz” if the number is divisible by 5, “fizz buzz” if the number is divisible by 15, and the input number otherwise.However, the current implementation has a bug. The
if
condition for checking whether the number is divisible by 15 should come before the conditions for checking whether the number is divisible by 3 and 5. This is because a number that is divisible by 15 is also divisible by 3 and 5, and the current implementation will return “fizz” or “buzz” instead of “fizz buzz” for such numbers.Here’s the corrected implementation:
PythonCopied!def fizzbuzz(number): if number % 15 == 0: return "fizz buzz" elif number % 3 == 0: return "fizz" elif number % 5 == 0: return "buzz" else: return number
With this correction, the function should behave as expected.
ChatGPT was able to spot the logical error in your code. It probably succeeded because this is a common programming assignment that must have many solutions and explanations in the language corpus that the model was trained on. But FizzBuzz won’t be the only example where ChatGPT’s suggestions will be able to help you at least get an idea of where you could look to identify the logical bug that’s hiding in your code.
Pair Program With ChatGPT and Write Better Code
You’ve learned how ChatGPT can help you debug your code to build more robust programs. You can use the tool for one-off questions like that. But ChatGPT can also work alongside you every step of the way to improve the code that you’ve written and help you learn better practices and style. You can use it as if you were pair programming with your coding mentor.
In this example, you’re developing a guess-the-number game. You’ve finished implementing the game, and it works well:
import random
num = random.randint(1, 100)
i = None
while i != num:
i = int(input("Guess the number: "))
if i < num:
print("Too low")
elif i > num:
print("Too high")
else:
print("Correct!")
With this working code example, you can head over to ChatGPT and find out whether your personal coding mentor has some suggestions on how you could improve this code. You could literally paste the code example followed by the question How can I improve this code? and you’d probably get some useful suggestions.
However, in this section, you’ll try to be a bit more specific and mention to ChatGPT what types of improvements you’re looking for. The variables aren’t named very descriptively in the code snippet above. But as many programmers might agree, naming things can be hard!
ChatGPT is based on a large language model, so naming things should be one of the tasks that it’s good at! Try asking ChatGPT to rename the objects for you:
You:
PythonCopied!import random num = random.randint(1, 100) i = None while i != num: i = int(input("Guess the number: ")) if i < num: print("Too low") elif i > num: print("Too high") else: print("Correct!")
How can I improve variable naming in this code example?
ChatGPT: The variable
num
andi
are somewhat clear in their purpose. However, you could improve their names to make the code more readable and self-explanatory. Here’s an example:PythonCopied!import random random_number = random.randint(1, 100) user_guess = None while user_guess != random_number: user_guess = int(input("Guess the number: ")) if user_guess < random_number: print("Too low") elif user_guess > random_number: print("Too high") else: print("Correct!")
In this version, the names
random_number
anduser_guess
are more descriptive and easier to understand at first glance. They make it clear what values the variables hold and what they are used for within the code.
Great! ChatGPT helped you to refactor your code by renaming your variables in a more descriptive manner. Because your coding mentor seems to be such a good communicator, you’ll also ask them to improve the user messages by asking a follow-up question:
You: Could you also improve the messages a user will read when interacting with this program?
ChatGPT: Sure! Here’s an updated version of the code with more user-friendly messages:
PythonCopied!import random random_number = random.randint(1, 100) user_guess = None while user_guess != random_number: user_guess = int(input("Guess a number between 1 and 100: ")) if user_guess < random_number: print("Your guess is too low. Try again!") elif user_guess > random_number: print("Your guess is too high. Try again!") else: print("Congratulations, you guessed the number correctly!")
In this updated version, the user is prompted to “Guess a number between 1 and 100” to make it clear what range of values they should be guessing. The messages for incorrect guesses have also been updated to provide more specific feedback.
For example, if the user guesses a number that is too low, the program will print the message “Your guess is too low. Try again!” Similarly, if the user guesses a number that is too high, the program will print the message “Your guess is too high. Try again!”.
These messages will help the user understand why their guess was incorrect and how they can adjust their strategy for the next guess.
ChatGPT added better user messages to your code, which will make it more understandable. Plus, your game may be even more fun for others to play. Now, what if you want to reuse this code in a different Python module? A good first step will be to refactor the code into a function that you can import.
This change brings a couple of advantages beyond making your code more modular. Overall, using functions can make your code more readable, reusable, and organized. And while you already know how to write a Python function, maybe ChatGPT can help you with this step as well:
You: Can you refactor the code into a function?
ChatGPT: Certainly! Here’s a refactored version of the code as a function:
PythonCopied!import random def guess_the_number(): random_number = random.randint(1, 100) user_guess = None while user_guess != random_number: user_guess = int(input("Guess a number between 1 and 100: ")) if user_guess < random_number: print("Your guess is too low. Try again!") elif user_guess > random_number: print("Your guess is too high. Try again!") else: print("Congratulations, you guessed the number correctly!")
Now you can call
guess_the_number()
to start the game. The function generates a random number between 1 and 100, prompts the user to guess a number, and provides feedback based on whether the guess was too low, too high, or correct.Using a function makes it easier to reuse this code elsewhere in your program, or even in other programs. It also makes the code easier to understand and modify, since the functionality is encapsulated in a single function with a clear name.
If you use the suggested code, then you can now import your Python program and start the game by calling guess_the_number()
. However, the function is quite limited at the moment. It might be a good idea to make it more flexible by not hard-coding the range and instead allowing users to add it when calling the function.
You could ask ChatGPT to make the change for you by typing a specific prompt that uses clear language and instructions:
You: Please refactor the code so that
1
and100
are default arguments. Also use an f-string to fix the input text message accordingly.
ChatGPT: Sure! Here’s a refactored version of the code with default arguments and an f-string for the input prompt:
PythonCopied!import random def guess_the_number(low=1, high=100): random_number = random.randint(low, high) user_guess = None while user_guess != random_number: user_guess = int(input(f"Guess a number between {low} and {high}: ")) if user_guess < random_number: print("Your guess is too low. Try again!") elif user_guess > random_number: print("Your guess is too high. Try again!") else: print("Congratulations, you guessed the number correctly!")
In this updated version,
low
andhigh
are added as default arguments to theguess_the_number()
function. Therandom_number
is now generated using these arguments, so you can specify a different range of numbers when calling the function.The input prompt also uses an f-string to include the
low
andhigh
values in the message, making it easier to understand what range of values the user should be guessing.You can now call
guess_the_number()
without arguments to use the default range of 1 to 100 or specify your own range, likeguess_the_number(10, 50)
, to use a range of 10 to 50.
This game is coming along nicely! In this step, you asked quite a specific question. This is the type of question that ChatGPT often works well with. But when you’re asking a common question, you might get good results even if you write an imprecise prompt.
You currently aren’t returning a value from the function, which means that you couldn’t keep track of guessed numbers if you were to build a game with multiple rounds. However, maybe you haven’t heard about the Python return
statement, and you just know how to describe the functionality that you’re looking for. So, you go ahead and ask ChatGPT what to do by using a general question:
You: How can I save the randomly generated number?
ChatGPT: One way to save the randomly generated number is to return it from the
guess_the_number()
function. Here’s an updated version of the code that does this:PythonCopied!import random def guess_the_number(low=1, high=100): random_number = random.randint(low, high) user_guess = None while user_guess != random_number: user_guess = int(input(f"Guess a number between {low} and {high}: ")) if user_guess < random_number: print("Your guess is too low. Try again!") elif user_guess > random_number: print("Your guess is too high. Try again!") else: print("Congratulations, you guessed the number correctly!") return random_number
In this updated version,
random_number
is returned from theguess_the_number()
function after the user guesses the correct number. You can now call the function like this:PythonCopied!random_number = guess_the_number() print(f"The randomly generated number was {random_number}.")
This will store the randomly generated number in the
random_number
variable, and print it out after the user has guessed the correct number.Note that you can also save the
random_number
to a file or database if you need to use it again later.
Great! Now you’ll be able to use the return value of the function to keep track of which numbers a user guessed, for example. You didn’t even mention return
in your question to ChatGPT! However, because this is a very common way to tackle the task that you described, ChatGPT went ahead and built a solution based on returning the value.
Note: Keep in mind that you’ll generally get better results if you ask specific questions with more context, and you’re more likely to get incorrect or irrelevant responses when your prompts are vague or general.
Finally, it’d be great to add docstrings and type hinting to your function as well, so you ask ChatGPT:
You: Could you also add type hinting and a docstring to the function?
ChatGPT: Sure, here’s the updated code with type hinting and a docstring:
PythonCopied!import random def guess_the_number(low: int = 1, high: int = 100) -> int: """ Plays a guessing game where the user must guess a random number between `low` and `high`. Returns the randomly generated number. Args: low (int): The lowest possible number in the range (default 1). high (int): The highest possible number in the range (default 100). Returns: int: The randomly generated number. """ random_number = random.randint(low, high) user_guess = None while user_guess != random_number: user_guess = int(input(f"Guess a number between {low} and {high}: ")) if user_guess < random_number: print("Your guess is too low. Try again!") elif user_guess > random_number: print("Your guess is too high. Try again!") else: print("Congratulations, you guessed the number correctly!") return random_number
In this version, we added type hints to the function parameters and return value. We also added a docstring that describes what the function does, what arguments it takes, and what it returns.
Using type hints and docstrings can make your code more clear and easier to understand, especially if you’re working with a team or sharing your code with others.
That looks quite good! ChatGPT created a Google-style docstring that almost fits the specification for multiline docstrings, and it added helpful type hints.
Note: The generated docstring is missing the first summary line, which should fit on a single line and come before the more elaborate description of what the function does. Can you prompt ChatGPT to add that summary line for you as well?
Using ChatGPT to document code can be a great help for developers who don’t like to write documentation. With ChatGPT, you can improve the quality and accessibility of your codebase without spending too much time on tasks that you’re less enthusiastic about.
Note: Here you used the conversational aspect of ChatGPT to incrementally improve your code, and the LLM kept the context of your previous prompts. Eventually you’ll hit a limit when the overall prompt that consists of all inputs and outputs becomes too large. ChatGPT will then stop using your text from the beginning of the prompt. For GPT-3, this cutoff point lies at 2048 tokens.
In this section, you didn’t make many changes to your code. Its functionality is still quite similar to what it was at the beginning. However, by prompting your ChatGPT coding mentor for its input, you found ways to improve and refactor your code toward better maintainability and reusability.
Prompt ChatGPT for Alternative Implementations
You’ve already learned that you can’t rely on the accuracy of the output you get from your ChatGPT Python mentor and that you always need to double-check the results. First and foremost, the output of an LLM is a great tool for creativity, and there’s a lot you can learn there.
Your ChatGPT mentor can provide you with several different solutions to a problem. This can broaden your horizons and allow you to explore new approaches to solving tasks. Think back to the common code interview question about FizzBuzz that you debugged with ChatGPT in an earlier section:
def fizzbuzz(number):
if number % 15 == 0:
return "fizz buzz"
elif number % 3 == 0:
return "fizz"
elif number % 5 == 0:
return "buzz"
else:
return number
Can you think of some other ways to solve this challenge? Maybe there are alternative implementations that you could consider. You could look for other people’s code on the Internet, or you could ask your ChatGPT coding mentor to show you some other solutions by inputting the code and typing a question:
You:
PythonCopied!def fizzbuzz(number): if number % 15 == 0: return "fizz buzz" elif number % 3 == 0: return "fizz" elif number % 5 == 0: return "buzz" else: return number
What are alternative implementations of this problem?
ChatGPT: The FizzBuzz problem is a common coding exercise that requires writing a program that prints numbers from 1 to n, but replaces multiples of 3 with “fizz”, multiples of 5 with “buzz”, and multiples of both 3 and 5 with “fizz buzz”. Here are some alternative implementations of the FizzBuzz problem in Python:
Using a for loop:
PythonCopied!def fizzbuzz(n): for i in range(1, n+1): if i % 15 == 0: print("fizz buzz") elif i % 3 == 0: print("fizz") elif i % 5 == 0: print("buzz") else: print(i)
Using list comprehension:
PythonCopied!def fizzbuzz(n): result = [ "fizz buzz" if i % 15 == 0 else "fizz" if i % 3 == 0 else "buzz" if i % 5 == 0 else i for i in range(1, n+1) ] return result
Using a generator expression:
PythonCopied!def fizzbuzz(n): return ( "fizz buzz" if i % 15 == 0 else "fizz" if i % 3 == 0 else "buzz" if i % 5 == 0 else i for i in range(1, n+1) )
Using a dictionary to map numbers to their corresponding strings:
PythonCopied!def fizzbuzz(n): mapping = {3: "fizz", 5: "buzz", 15: "fizz buzz"} for i in range(1, n+1): output = "" for key in mapping: if i % key == 0: output += mapping[key] if output == "": output = i print(output)
These are just a few examples of how the FizzBuzz problem can be implemented in Python. There are many other possible solutions and variations on this problem.
Right away, ChatGPT offered you four alternative implementations that claim to solve the same task. You might notice that all of the solutions work on a range()
instead of on a single number, like your initial example did.
Note: While the example code that ChatGPT provided follows PEP-8, it’ll run into error E226 when you’re linting the code with flake8. This error comes up because there’s no whitespace around the +
operator in n+1
. The code formatter Black will also add that whitespace.
It’s notable that PEP-8 doesn’t require the whitespace, but programmers generally include it. You might not always learn the best practices when following ChatGPT’s coding style.
While the implementations that ChatGPT suggested don’t strictly solve the same task as the code you provided, they can give you an idea of how you might want to change or extend your original code.
The first suggestion uses a for
loop to iterate over the range that ChatGPT introduced. Apart from that, there aren’t many changes:
def fizzbuzz(n):
for i in range(1, n+1):
if i % 15 == 0:
print("fizz buzz")
elif i % 3 == 0:
print("fizz")
elif i % 5 == 0:
print("buzz")
else:
print(i)
ChatGPT rewrote the code so that it now operates on a range of numbers instead of a single number. This is likely the more common way to tackle the FizzBuzz challenge. In fact, if you ask ChatGPT what the rules of FizzBuzz are, then you’ll quickly see that looping is usually a part of the challenge:
You: What are the rules of FizzBuzz?
ChatGPT: FizzBuzz is a simple programming problem that is often used in job interviews to assess a candidate’s ability to write basic code. The rules of FizzBuzz are as follows:
- Print the numbers from 1 to 100.
- For each number that is a multiple of 3, print “Fizz” instead of the number.
- For each number that is a multiple of 5, print “Buzz” instead of the number.
- For each number that is a multiple of both 3 and 5, print “FizzBuzz” instead of the number.
So, in short, the program should output a sequence of numbers from 1 to 100, but replacing the numbers that are multiples of 3 with the word “Fizz”, replacing the multiples of 5 with the word “Buzz”, and replacing the multiples of both 3 and 5 with the word “FizzBuzz”.
You can always get more context for the task that you’re facing by asking ChatGPT additional questions.
The second and third suggestions are similar to each other. One solves the task using a list comprehension, while the other uses a generator expression. The code is similar, but the list comprehension executes immediately, while the generator expression executes lazily:
# List comprehension
def fizzbuzz(n):
result = [
"fizz buzz"
if i % 15 == 0
else "fizz"
if i % 3 == 0
else "buzz"
if i % 5 == 0
else i
for i in range(1, n+1)
]
return result
# Generator expression
def fizzbuzz(n):
return (
"fizz buzz"
if i % 15 == 0
else "fizz"
if i % 3 == 0
else "buzz"
if i % 5 == 0
else i
for i in range(1, n+1)
)
While the code looks similar, you can again see some subtle differences. The code for the list comprehension introduces an intermediate variable, result
, while the example that solves the challenge using a generator expression returns the generator object directly.
Note that you’ll also have to run the two examples differently because of their different evaluation methods. If you want to try the examples, then you can download the example code:
Free Bonus: Click here to download the free sample code and engineered prompts that show you how to boost your Python programming skills with the help of ChatGPT.
While these two one-liner solutions produce the expected results, they’re pretty difficult to read and understand. As a result, they’ll also be more difficult to maintain. ChatGPT showed you alternative solutions, but that doesn’t mean that you should implement them in your codebase.
Note: Generally, to write cleaner, more Pythonic code, it’s a good idea to focus your efforts on making the code as readable as possible.
Finally, ChatGPT also presented you with a fourth code snippet where it uses a dictionary to map numbers to corresponding strings:
def fizzbuzz(n):
mapping = {3: "fizz", 5: "buzz", 15: "fizz buzz"}
for i in range(1, n+1):
output = ""
for key in mapping:
if i % key == 0:
output += mapping[key]
if output == "":
output = i
print(output)
Here it attempts to use dictionary lookups to decide which string to print. However, this implementation is both hard to read and incorrect. A good way to confirm whether ChatGPT produced code that solves your challenge is to try it out. When you run the code snippet on a range of fifteen, then you’ll notice the bug in the code:
>>> fizzbuzz(15)
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzzfizz buzz
While the beginning of the output looks promising, the code produces incorrect results when it encounters a number that’s divisible by more than one of the numbers.
This happens because you’re iterating over the dictionary keys and applying the conditional check using the modulo operator on each of the keys. Therefore, if the current number of the loop is evenly divisible by more than one of the numbers, then each of the associated strings will make it into output
.
Note: While running code generated by ChatGPT to confirm its functionality is often helpful, you also need to keep your safety in mind. If you don’t know what a generated piece of code does, then you should pause and think before running it. You can also ask ChatGPT to walk you through the code’s functionality!
ChatGPT isn’t always correct, but it also produced a couple of relevant suggestions that show you alternative implementations of the FizzBuzz challenge. If you consider your ChatGPT coding mentor highly creative and wildly unaware, then you can appreciate its suggestions while also remembering to double-check them.
And of course, you can also learn a lot from incorrect and buggy code through, for example, reasoning why the fourth solution that ChatGPT suggested doesn’t solve the challenge correctly.
Get Answers to Your Programming Questions
Another good use case for interacting with ChatGPT as your Python coding mentor is to ask questions that you have about general programming or Python concepts.
For example, you could ask ChatGPT about the difference between lists and tuples, two Python data types that are sometimes confusing for learners who are new to programming:
You: What’s the difference between a list and a tuple in Python?
ChatGPT: In Python, both lists and tuples are used to store collections of data. However, there are some key differences between the two:
Mutability: The main difference between lists and tuples is that lists are mutable (can be changed), while tuples are immutable (cannot be changed). This means that once a tuple is created, you cannot add, remove, or modify any of its elements, whereas you can do all of these things with a list.
Syntax: Lists are defined using square brackets [], while tuples are defined using parentheses (). For example:
PythonCopied!my_list = [1, 2, 3] my_tuple = (1, 2, 3)
Usage: Lists are typically used when you need to store a collection of items that you may want to modify or rearrange later. Tuples, on the other hand, are used when you need to store a collection of items that will not change, such as a set of coordinates or a date and time.
Performance: Tuples are generally faster than lists for accessing elements, since they are stored in memory as a contiguous block. Lists, on the other hand, may need to allocate new memory and copy elements over if they grow beyond their initial capacity.
In summary, lists are mutable, defined using square brackets, and are used when you need to store a collection of items that you may want to modify or rearrange later. Tuples are immutable, defined using parentheses, and are used when you need to store a collection of items that will not change.
If this answer still contains too many new terms for you, then you can continue to ask ChatGPT clarifying questions. After all, your coding mentor is conversational! For example, you could ask follow up questions such as:
- What’s the difference between mutable vs immutable types
- Can you show me a real-world example of both a tuple and a list?
- What are good use cases for a tuple?
You might get pretty good answers to these questions. However—as always—you need to keep in mind that ChatGPT only strings together word tokens based on probability, which means that you can’t rely on the answers you get. You should always check and confirm.
Note: When ChatGPT discussed performance of tuples and lists, it said that tuples are generally faster than lists for accessing elements. This is true. However, its reasoning isn’t accurate. Python doesn’t allocate new memory or copy elements when accessing list elements. Be careful with any statement the model makes.
The answer that you see above is only based on the short prompt at the beginning of the quote block. You might be able to improve the answer even further by engineering a better prompt like you saw in an earlier section.
One way of adding credibility to an answer is by checking the source. While ChatGPT doesn’t yet provide sources directly, you can ask it to provide its sources and links:
You: Please provide some links that explain the topic.
Browse the links that it offers and make sure the information checks out. Look for reputable sites! Just like you shouldn’t automatically trust the probabilistic token strings that your ChatGPT coding mentor assembles, you also shouldn’t trust all the writing you encounter on the Internet. But you’ve probably been around the Web for long enough to know that!
Keeping with the topic of links, another great way to use your ChatGPT coding mentor when you’re learning about Python is to ask it for links to certain parts of Python’s documentation. If you’ve struggled with the search feature in the Python docs, then you can let ChatGPT take care of that for you.
For example, you might want to gain a general understanding of how to use the __init__.py
file, but when you use the search in Python’s documentation, you get a lot of unrelated results:
It might take you a while to weed your way through these links, and if you read through the suggested results, you might get more confused than enlightened. Alternatively, you can send a prompt to your ChatGPT coding mentor to get a direct link:
You: Please show me the link to the Python documentation that explains
__init__.py
.
ChatGPT: Certainly! Here is a link to the Python documentation that explains the
__init__.py
file:https://docs.python.org/3/tutorial/modules.html#packages
This page provides an overview of packages in Python and how to create them, including the purpose and usage of the
__init__.py
file.
ChatGPT doesn’t perform a classic search, but instead generates text based on probabilistic proximity. Because of that, it may be able to tackle some information retrieval situations like the one shown above better than a search algorithm.
The LLM behind ChatGPT has been trained on a large corpus of data, and it’s quite good at answering general programming questions. To double-check the answers that you get, you can ask it to provide you with links to sources, which will allow you to make sure that the model didn’t hallucinate.
Next Steps
Now that you’ve worked through some examples of how you can use ChatGPT to enhance your Python learning, here are some next steps that you can take with your ChatGPT coding mentor:
- Prompt ChatGPT for project ideas and implementation tips—for example, which libraries to use for a project.
- Build one of the suggested projects by pair programming with ChatGPT—and make sure that the project works!
- Refactor one of your existing projects to improve code quality.
- Let ChatGPT write tests for your project code.
- Generate documentation for a project using ChatGPT.
If you struggle to get useful answers from ChatGPT, then you can learn prompting as a way to get better results.
Generative models, such as GPT-3.5, are tools that can increase your productivity and help you on your learning journey, just like a coding mentor does. Of course, typing text prompts for an LLM is different from interacting with a knowledgeable and friendly human mentor like the ones you meet at Real Python Office Hours.
However, there’s something to be said for ChatGPT’s vast source data that it draws from. The LLM is also constantly available, while a human mentor will only have a limited amount of time.
On the flip side, a human mentor will likely be more demanding. They’ll try to make sure that you’re really learning. As a probability-based text-completion algorithm, ChatGPT can’t do that. Therefore, your learning progress is even more strongly—and literally—tied to your input.
Conclusion
Conversing with ChatGPT as your Python coding mentor is like joining a creative writing class for programmers. You can gain ideas, and it can help you tackle problems from angles that you haven’t thought about before.
In this tutorial, you’ve learned how to:
- Get ChatGPT up and running
- Use ChatGPT for code debugging
- Improve the style and quality of your code
- Work with ChatGPT on pair programming
- Solve a coding task in different ways
- Ask programming questions and get answers
While ChatGPT can be a helpful learning tool, you always need to stay aware of its limitations. ChatGPT doesn’t think or assess the quality of the text that it produces. It just strings together tokens based on probability. Its answers can be biased, irrelevant, incorrect, and even completely made up.
That said, there are always useful and less useful ways to use any tool. You know that it’s better to use a hammer for driving in nails than for flipping pancakes. ChatGPT isn’t great at flipping pancakes either, but it’s still a tool that you can use for your Python studies. Have you found other use cases for ChatGPT in your daily Python workflow? Let everyone know in the comments below.
Free Bonus: Click here to download the free sample code and engineered prompts that show you how to boost your Python programming skills with the help of ChatGPT.