AI and programming in Python#

Attention

Finnish university students are encouraged to use the CSC Noppe platform.
CSC badge

Others can follow the lesson and fill in their student notebooks using Binder.
Binder badge

Warning

The aim of this lesson is to familarize you with the use of AI and large language models for producing code. The main objective is to show the potentials and risks of these newly arising tools for programming. However, other than where explicitly stated in the exercises, we do not encourage use of these tools in this course.

Note

The codes produced by ChatGPT in this lesson are not necessarily examples of good Python codes.

Sources#

The Python code examples in this lesson were produced by the ChatGPT application by OpenAI.

AI and LLM#

AI, or Artificial Intelligence, refers to the field of computer science dedicated to developing systems and algorithms that enable machines to perform tasks typically requiring human intelligence, such as problem-solving, learning, and natural language understanding. On the other hand, LLM, or Large Language Models, are a specific category of AI models designed to process and generate human language text. ChatGPT (Chat Generative Pre-trained Transformer) is one common example of an LLM, created by OpenAI. ChatGPT excels in understanding and generating human-like text, making it useful for tasks like chatbots, virtual assistants, and content generation.

Getting started with ChatGPT#

In order to use ChatGPT you will first need to create an account on OpenAI. If you already have an account, you can login using your account. If you are new to OpenAI, you can create a new account for free. Click on the Get Started button to go to the signup page. Here you can create an account using your email or by linking it to another of your accounts (such as Google). In order to sign up, you need to provide your email address, mobile phone number, and date of birth (!). Doing this is voluntary for this course.

ChatGPT signp

Once you have created your account and activated it, you can login to access ChatGPT.

Using ChatGPT#

You can communicate with ChatGPT using the prompt at the bottom of the page (where it reads “Send a message”).

ChatGPT

A prompt is a specific instruction, query, or input provided to a computer program or artificial intelligence system to elicit a desired response or output. In the context of language models like ChatGPT, a prompt typically consists of a text-based request or question that users provide to the model. The model generates a response based on the content and context of the prompt. Prompts are used to interact with AI systems, instruct them on what task to perform, or seek information or assistance from them. The quality and clarity of the prompt can significantly impact the accuracy and relevance of the AI’s response.

Lets start with an example prompt we can type in:

Write a Python function that adds two numbers

Response:

def add_numbers(a, b):
    return a + b

OK, so we clearly got back a Python function that appears to work to add two numbers. Cool!

ChatGPT remembers your conversation (i.e., history of prompts). So you can ask it to modify a previously provided response for you. Let’s try this with another prompt.

Give me an example of using the output of this function in an f-string

Response:

def add_numbers(a, b):

    return a + b

num1 = 5
num2 = 3
result = add_numbers(num1, num2)
formatted_string = f"The sum of {num1} and {num2} is {result}."
print(formatted_string)
The sum of 5 and 3 is 8.

OK, so it remembered our function and did as requested.

Let’s try another prompt:

Add inline comments to the code

Response:

# Define a function that takes two numbers as input and returns their sum.
def add_numbers(a, b):
    """
    This function takes two numbers as input and returns their sum.
    
    :param a: The first number to be added.
    :param b: The second number to be added.
    :return: The sum of the two input numbers.
    """
    return a + b

# Define two numbers to be added.
num1 = 5
num2 = 3

# Call the add_numbers function and store the result in the 'result' variable.
result = add_numbers(num1, num2)

# Using an f-string to format the output and include variable values.
formatted_string = f"The sum of {num1} and {num2} is {result}."

# Print the formatted string.
print(formatted_string)
The sum of 5 and 3 is 8.

Wow! It seems that ChatGPT is quite capable for this kind of task.

Note

The same prompt can yield different responses from ChatGPT due to factors such as randomness in word selection, variations in model versions and training data, contextual influences from preceding dialogue, ambiguity in prompts, settings, response length parameters, and the model’s exposure to diverse internet text. Additionally, fine-tuning for specific tasks, user feedback, and evolving preferences can all contribute to the diversity of generated responses.

Let’s try another prompt:

Write me a python function that converts degrees Fahrenheit to Celsius

Response:

def fahrenheit_to_celsius(fahrenheit):
    """
    Converts a temperature from degrees Fahrenheit to degrees Celsius.

    :param fahrenheit: Temperature in degrees Fahrenheit
    :return: Temperature in degrees Celsius
    """
    celsius = (fahrenheit - 32) * 5/9
    return celsius

Now let’s test this function.

# Write your code below
fahrenheit_temperature = 68  
celsius_temperature = fahrenheit_to_celsius(fahrenheit_temperature)

print(f"{fahrenheit_temperature} degrees Fahrenheit is equal to {celsius_temperature:.2f} degrees Celsius.")
68 degrees Fahrenheit is equal to 20.00 degrees Celsius.

It seems that things are working, at least in our example output from ChatGPT.

Writing good prompts#

Remember that you are talking with a machine in your prompts. So it is very important for you to provide prompts that are clear and have clear objectives. In your prompts, try to provide as much context and instruction as possible.

Here’s an example of a bad prompt:

A function to convert Kelvin to Newton

Response:

def kelvin_to_newton(mass_kg, acceleration_m_s2):
    force_newton = mass_kg * acceleration_m_s2
    return force_newton

This doesn’t look correct, as we were aiming to convert from Kelvins to degrees Newton, as we did in the functions lesson.

Let’s write this better by adding more context:

A function to convert temperature in Kelvin to Newton
def kelvin_to_newton(kelvin_temperature):
    newton_temperature = kelvin_temperature * 0.33
    return newton_temperature

OK, so now we get a better looking function that at least has something about a temperature conversion.

Check your understanding#

This is a good example of a better prompt, but something is still not quite right about this output code. Can you identify any potential problems with the function created above?

Enter your ideas and vote on the suggestions at https://geo-python.github.io/poll/.

Testing ChatGPT-generated code#

Now we can test out our temperature conversion function using a list of temperatures in Kelvins.

# Write your code below
kelvin_temperatures = [100, 200, 300, 400, 500]
print (kelvin_to_newton(kelvin_temperatures))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[8], line 3
      1 # Write your code below
      2 kelvin_temperatures = [100, 200, 300, 400, 500]
----> 3 print (kelvin_to_newton(kelvin_temperatures))

Cell In[7], line 2, in kelvin_to_newton(kelvin_temperature)
      1 def kelvin_to_newton(kelvin_temperature):
----> 2     newton_temperature = kelvin_temperature * 0.33
      3     return newton_temperature

TypeError: can't multiply sequence by non-int of type 'float'

Oh, no! This results in an error as the function is not designed to receive a list as input.

We can resolve this issue by writing our prompt more precisely:

Give me a python function to convert a list of temperatures in degrees Kelvin to Newton and print out the results

Response:

def kelvin_to_newton(temperature_k):
    return temperature_k * 0.33

def convert_and_print_temperatures(kelvin_temperatures):
    print("Kelvin to Newton Conversion:")
    for temp_k in kelvin_temperatures:
        temp_n = kelvin_to_newton(temp_k)
        print(f"{temp_k} K is equal to {temp_n:.2f} N")

Now let’s test things out with the same list of temperatures in Kelvins from above.

# Write your code below
kelvin_temperatures = [100, 200, 300, 400, 500]
convert_and_print_temperatures(kelvin_temperatures)
Kelvin to Newton Conversion:
100 K is equal to 33.00 N
200 K is equal to 66.00 N
300 K is equal to 99.00 N
400 K is equal to 132.00 N
500 K is equal to 165.00 N

OK, so it seems the function now handles lists of temperatures without any trouble. Let’s see if we can now create a new function that classifies temperatures into five classes. We can start with this prompt:

Create a python function that classifies an input temperature to five classes

Response:

def create_temperature_classifier():
    def classify_temperature(temperature):
        if temperature < 0:
            return "Below Freezing"
        elif 0 <= temperature < 20:
            return "Cold"
        elif 20 <= temperature < 40:
            return "Cool"
        elif 40 <= temperature < 60:
            return "Moderate"
        elif 60 <= temperature < 80:
            return "Warm"
        else:
            return "Hot"
    return classify_temperature

This works, but it is a vague prompt that does not specify the temperature unit or the classification logic needed. And ChatGPT provides a strange solution using an unnecesssary nested function for it. In addition, it is actually creating 6 classes instead of 5.

Regardless, let’s see how it works:

classify_temp = create_temperature_classifier()
temperature = 35
category = classify_temp(temperature)
print(f"The temperature {temperature}°C is classified as {category}")
The temperature 35°C is classified as Cool

OK, so there are some issues… Perhaps we could do better by using the ChatGPT code as a starting place and modifying things to make more sense for our use:

# Write your code below
def classify_temperature(temperature):
    if temperature < 0:
        return "Below Freezing"
    elif 0 <= temperature < 20:
        return "Cold"
    elif 20 <= temperature < 40:
        return "Cool"
    elif 40 <= temperature < 60:
        return "Moderate"
    elif 60 <= temperature < 80:
        return "Warm"
    else:
        return "Hot"

Let’s start with a basic test of the function with negative temperatures:

# Write your code below
temp1 = -1
temp2 = -60
cat1 = classify_temperature(temp1)
cat2 = classify_temperature(temp2)
print(f"The temperature {temp1}°C is classified as {cat1}")
print(f"The temperature {temp2}°C is classified as {cat2}")
The temperature -1°C is classified as Below Freezing
The temperature -60°C is classified as Below Freezing

According to this function -60 and -1 are both in the same class!

Privacy matters#

It’s important to exercise caution when sharing personal or sensitive information with AI models like ChatGPT. While these models are designed to provide helpful information and engage in conversations, they don’t have the ability to understand the implications of sharing sensitive data or guarantee complete privacy. Avoid sharing confidential information such as personal identification numbers, passwords, financial details, or any data that could compromise your privacy or security. Always remember that interactions with AI should be treated as public, and it’s best to prioritize your privacy and safety online.

Conclusion#

ChatGPT, as an example of a LLM, can be a useful tool for creating parts of code when used with clear and specific prompts. Good prompts may yield useful code, while vague or unclear prompts usually result in unhelpful or wrong responses. Remember to be aware of ChatGPT’s limitations and thoroughly review the generated code to ensure it meets your requirements and standards.

ChatGPT has limitations, and it is important to be aware of them:

  • Lack of Context: ChatGPT generates code based on the provided prompt, but it may not understand the broader context of your project or requirements.

  • Complex Logic: While ChatGPT can handle simple functions well, it may struggle with complex logic, intricate algorithms, or code that requires domain-specific knowledge.

  • Testing: Always thoroughly test the code generated by ChatGPT to ensure it functions as expected and doesn’t have vulnerabilities.

  • Security: Be cautious when using ChatGPT to generate code for security-critical applications, as it may not consider all security risks.

AI models can help you with certain tasks but be cautious with how you use them. The results can vary significantly depending on your prompt. Where there is nor information or context provided, the model makes assumptions which may not be accurate. And remember not to fully trust the result, AIs are smart but they DO make mistakes sometimes.