ChatGPT: How to Use It To Write Python Code?

Today I’m writing about ChatGPT and how it can help you with coding. I used this AI tool to write a simple Flask application in Python in a matter of minutes. At the same time, I want to show how it can be used to have fun and help you work on your creative process. If you are interested in these types of posts, I recently also covered Stable Diffusion, a latent diffusion model that can generate images from a prompt.

What Is ChatGPT?

If you have been reading the news lately, you probably heard about ChatGPT at some point. ChatGPT is the latest large-language model from OpenAI. Their previous language model was GPT-3. Although ChatGPT is a smaller model than GPT-3 (20 billion parameters vs 175 billion), it seems to have been fine-tuned and trained for conversation applications.

You can find examples of hilarious responses when you ask it to be creative. At the same time, I find the moral judgments and warnings on every response to be annoying sometimes. It has also been trained to refuse to answer certain problematic prompts. There are ways to creatively circumvent those restrictions, such as this Reddit example, or this one.

Resources

If you are looking for a great resource on machine learning, I recommend the third edition of Aurélien Géron’s O’Reilly book: “Hands-On Machine Learning With Scikit-Learn, Keras & Tensorflow”.

The new edition came out in October of 2022 and has more up-to-date information on transformers and diffusion models. It also covers topics such as supervised and unsupervised learning, random forests, deep learning, natural language processing, and training and deploying TensorFlow models, among many more topics. It also includes a whole section on natural language processing or NLP and transformers, the machine learning architecture behind GPT-4.

So, if you are interested, you can get it here using my referral link. The price is the same to you, but I might get a commission.

One other thing I like about the book is that it includes an end-to-end machine learning project to learn the entire pipeline of a data scientist.

ChatGPT For Coding

I want to use this section to show one example of how to use ChatGPT to code. The idea is that maybe it will help in cutting down the time needed for boilerplate code. I have not used GitHub’s Co-Pilot tool, but I imagine it works in a similar way, and both use OpenAI’s technology. If you want to give it a try yourself, here is the demo page. You will need to create an account with OpenAI, but it is a quick process.

I will show one example of what ChatGPT can do when asked to write code. You can also check this quick video I made about it as well:

Example: Write a Simple Flask Webapp To Calculate a User’s BMI

I asked ChatGPT to write a python script using Flask, where users input their height and weight and the application returns their BMI.

My initial prompt was:

write a flask application in python that calculates a user’s BMI. It should take two inputs: height and weight. There should also be a button to switch between metric system and imperial units. The program should display the calculated BMI with up to 2 decimals.

Here is a little snippet of ChatGPT’s response to my request:

Here is a short video of ChatGPT generating the code I asked for, in real-time.

I find it impressive that it is able to create all the files needed to run this application in a coherent manner. First, it wrote the Python side correctly and even included a form option for the unit type. Then, ChatGPT wrote the HTML code needed to display the application. Amazingly, all variable names match the ones that Flask is sending from the Python side.

The web app looks like this:

Pure HTML Flask application written entirely by ChatGPT with a simple prompt
Pure HTML Flask application written entirely by ChatGPT with a simple prompt

It uses plain HTML that looks very basic. However, ChatGPT was able to include a button to switch between imperial and metric systems. If you take a look at the Flask code, you will see that internally it also uses different calculations for both. Unfortunately, it did not add labels for units: kg vs g for metric, feet vs inches for imperial, etc.

At first, ChatGPT displayed the results on a different page, so I asked it to modify bmi_calculator.html to show the output on the same page.

I followed up the conversation with more prompts, asking ChatGPT to make the HTML better-looking and to add labels for the units for each input. The new code includes some CSS in the HTML file.

Here you can see the final version:

ChatGPT added some CSS to the bmi_calculator.html code to make the application look nicer and centered.
ChatGPT added some CSS to the bmi_calculator.html code to make the application look nicer and centered.

The Code

You can take a look at the whole conversation using the link above but I’m also including the final code I used for the screenshots above.

  • app.py
from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def bmi_calculator():
    return render_template('bmi_calculator.html')

@app.route('/calculate', methods=['POST'])
def calculate():
    height = float(request.form['height'])
    weight = float(request.form['weight'])
    units = request.form['units']

    if units == 'metric':
        bmi = weight / (height ** 2)
    else:
        bmi = 703 * (weight / (height ** 2))

    return render_template('bmi_calculator.html', bmi=bmi, units=units)

if __name__ == '__main__':
    app.run()
  • bmi_calculator.html
<html>
  <head>
    <style>
      body {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
      }
      form {
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      label {
        margin-top: 10px;
      }
      input[type="text"] {
        width: 50%;
        height: 30px;
        font-size: 16px;
        border: 1px solid #ccc;
        border-radius: 4px;
        padding: 10px;
      }
      input[type="submit"] {
        width: 50%;
        height: 40px;
        font-size: 18px;
        border: none;
        border-radius: 4px;
        background-color: #4CAF50;
        color: white;
        cursor: pointer;
      }
      input[type="submit"]:hover {
        background-color: #45a049;
      }
      p {
        font-size: 18px;
        margin-top: 20px;
      }
    </style>
  </head>
  <body>
    <form action="/calculate" method="post">
      <label for="height">Height:</label>
      {% if units == 'metric' %}
        <label style="margin-left: 10px;">in meters</label><br>
      {% else %}
        <label style="margin-left: 10px;">in inches</label><br>
      {% endif %}
      <input type="text" id="height" name="height"><br>
      <label for="weight">Weight:</label>
      {% if units == 'metric' %}
        <label style="margin-left: 10px;">in kg</label><br>
      {% else %}
        <label style="margin-left: 10px;">in pounds</label><br>
      {% endif %}
      <input type="text" id="weight" name="weight"><br>
      <input type="radio" id="metric" name="units" value="metric" checked>
      <label for="metric">Metric</label><br>
      <input type="radio" id="imperial" name="units" value="imperial">
      <label for="imperial">Imperial</label><br>
      <input type="submit" value="Calculate">
      {% if bmi %}
        <p>Your BMI is {{ bmi | round(2) }}</p>
      {% endif %}
    </form>
  </body>
</html>

I had a problem getting the unit labels to update when selecting a different radio button option. I’m not actually very proficient with HTML, but I would think that it shouldn’t be too complicated to accomplish that.

In case you are curious, the whole conversation with ChatGPT to generate this code is here, thanks to an open-source Chrome extension, ShareGPT, that allows you to easily share ChatGPT conversations with a single link. You can check the extension’s repository here.

Other Uses for ChatGPT

In my opinion, ChatGPT can give you a template/starting code that will save a lot of development time. I have seen a video of a game developer using it to write different C# scripts for Unity. It still requires supervision and you will need to correct some mistakes.

Another possible use case for ChatGPT could be to help with designing UI/UX for an application.

Personally, I’m interested in game development, so maybe I can use ChatGPT to springboard ideas for world-building and character design. This use will help with the programming side, although indirectly.

Conclusion

I just wanted to share an example of how you can use ChatGPT to help you with your coding projects. Notably, ChatGPT was able to write a fully-functional Python web app with Flask in just a matter of minutes. I had to guide it toward what I wanted, but the final result did the job. I find that feat impressive, to be honest.

If you have other use cases, let me know in the comments. Also, you can share links to interesting conversations you have with the AI.

You can also subscribe to my YouTube channel for videos on Python projects, automation, and crypto:

Finally, if you want to stay connected and up to date on what I post, you can join my newsletter here. I want this newsletter to be a useful resource of tips and tricks I learn and also a place to talk about new projects I might work on.

Have anything in mind?