AI and programming in Python#
AI tools can eventually be a useful collaborator once you know how to code yourself: explaining an error message, or speeding up something routine. But that’s not where you are yet. Right now, your job is to build the skill of reading, writing, and reasoning about code on your own. This lesson shows you both the strengths and limitations of AI-generated code, highlighting where and why it can fail. The goal is to approach AI with a healthy skepticism and understand its limitations, rather than seeing it as a shortcut.
Attention
You are learning Python for the first time. Read this lesson carefully before you use any AI tool for your coursework.
Warning
As a beginner, you should be cautious about using AI to write code for you. You are here to learn how to code, not to learn how to prompt something else to code for you. If you let AI write your solutions now, you skip the struggle that actually builds the skill, and you won’t have the experience needed to notice when it gets something wrong. Use AI tools sparingly at this stage, and only in the ways the course explicitly permits.
Note
The code examples in this lesson were produced by an AI chat assistant. They are not always examples of good Python code – that’s part of the point.
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. Such tools excel in understanding and generating human-like text, making it useful for tasks like chatbots, virtual assistants, and content generation. It’s just one example, other widely used LLM-based tools include Claude, Gemini, and AI features built directly into code editors like GitHub Copilot, Claude Code, and Cursor.
🤖 Using AI at the University of Helsinki
The University of Helsinki permits the use of generative AI in teaching and learning, unless a course or assignment specifically restricts it. The important point is that AI use should support your learning and follow the instructions given for each course.
Use University-provided AI services
If you use AI for your coursework, the University provides two services:
CurreChat: the University’s own generative AI service, designed specifically for educational use and with particular attention to data protection.
Microsoft Copilot with commercial data protection: available to both students and staff.
These services are the recommended options when working with university coursework, particularly when your work involves course materials or other potentially sensitive information.
📖 Read the University of Helsinki guidelines on AI in teaching for more information.
Accessing Microsoft Copilot#
Students at the University of Helsinki have access to Microsoft Copilot as part of the Microsoft 365 services provided by the University. You can access it at m365.cloud.microsoft/chat.
If you are joining this course from another university, you may have access to a similar AI service through your institution. If you are unsure, check with your university.

What about CurreChat?#
This course does not use CurreChat, but you may encounter it in other courses at the University of Helsinki.
CurreChat is the University of Helsinki’s own generative AI service, developed specifically for teaching and learning. It uses OpenAI models hosted in the University’s Microsoft Azure environment in the EU and is designed to meet the University’s data protection requirements. Information entered into CurreChat is not used to train the AI models.
If you have access to CurreChat, you can use it at curre.helsinki.fi/chat. It works much like other AI chatbots: you interact with it through a chat interface by asking questions or giving it instructions.

This lesson uses Microsoft Copilot for its examples, but the same principles apply to CurreChat and other AI tools, including Claude, Gemini, and other commercial AI assistants.
Using an AI chat assistant#
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 Copilot, 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!
Most AI chat assistants remember 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.
It seems like the assistant is quite capable for this kind of task.
Note
The same prompt can yield different responses – even from the same tool – 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 this example.
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 AI-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 the assistant 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 AI-generated 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!
Note
AI models keep improving, so a prompt like this one might not produce the exact same bug if you try it today – newer models are often better at simple counting/logic tasks. That doesn’t mean the risk is gone, though; it just shows up in different, sometimes less obvious places, like the example below.
A different kind of mistake: hallucinated code#
The examples above involved an AI misunderstanding what you wanted. There’s a second, sneakier category of mistake: the AI confidently using a function, method, or parameter that doesn’t actually exist. This is called a hallucination, and unlike the counting mistakes above, it doesn’t reliably get better as models improve – it can happen with even the most capable current models, especially for less common libraries.
This matters a lot for specialized work such as GIS, because geospatial libraries like geopandas and shapely are far less represented in AI training data than, say, general Python or web development code. Let’s see an example.
Suppose we ask an AI assistant:
Write a function that takes a GeoDataFrame of points and a reference point, and returns the GeoDataFrame with a new column giving the distance in kilometers from each point to the reference point.
Response:
# This is what an AI assistant might confidently hand back:
def add_distance_km(gdf, reference_point):
gdf["distance_km"] = gdf.geometry.distance_km(reference_point)
return gdf
Looks tidy. Let’s try running it:
add_distance_km(my_points_gdf, reference_point)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[16], line 1
----> 1 add_distance_km(my_points_gdf, reference_point)
NameError: name 'my_points_gdf' is not defined
There’s no such thing as .distance_km() in geopandas – the AI invented a method name that sounds entirely plausible, because .distance() does exist. This is the hallmark of a hallucination: it’s not a typo, it’s a fabricated API that reads as completely natural. Nothing about the code looks wrong until you actually run it.
And even the real .distance() method hides a second, very GIS-specific trap: it returns distances in whatever unit your GeoDataFrame’s CRS uses. If your data is in EPSG:4326 (lat/lon, degrees), .distance() gives you degrees – not meters, and definitely not kilometers. A correct version needs to reproject to a projected CRS first:
# A corrected version
def add_distance_km(gdf, reference_point):
# Reproject to a projected CRS (meters) before measuring distance -- e.g. UTM
gdf_projected = gdf.to_crs(gdf.estimate_utm_crs())
ref_projected = reference_point # assume already reprojected to match
gdf["distance_km"] = gdf_projected.geometry.distance(ref_projected) / 1000
return gdf
Note
You would only catch either of these problems – the invented method, and the CRS/units trap – by already knowing enough geopandas to recognize what a real method looks like, and enough GIS fundamentals to know that distance depends on your coordinate reference system. An AI assistant won’t reliably flag this for you; it produced the wrong answer just as confidently as it would produce a right one.
Staying the brain#
Notice what happened across all the examples above: misunderstood intent (the Kelvin-to-Newton mix-up), a quiet logic bug (-60°C and -1°C landing in the same class), and an outright fabricated method that only failed when we actually ran it (.distance_km()). These aren’t edge cases – they’re the normal experience of working with AI-generated code, and they don’t all go away as models get smarter. Hallucinated APIs in particular are still common with today’s best models, especially for less mainstream libraries like the geospatial ones you’ll use in this course.
As a beginner, this should make you more cautious about using AI to write your code, not less:
You can’t catch a mistake you don’t have the skill to recognize. An experienced programmer looked at the -60/-1 bug above and spotted it immediately. Right now, you likely couldn’t – which is exactly why relying on AI at this stage is risky, not convenient.
Outsourcing the writing outsources the learning. The struggle of writing code yourself – getting it wrong, debugging it, understanding why it broke – is how you actually build programming skill. If AI writes it for you, you skip the part where the learning happens.
Always run and test any code, with values you know the answer to, if you do use AI-generated code for any reason.
Read every line and be able to explain it. If you can’t explain what a piece of code does, don’t submit it as your own work.
Vague prompts get vague or wrong answers, and a confident-sounding answer is not the same as a correct one – AI text reads fluently whether it’s right or wrong.
You are responsible for the code you submit, full stop.
The bottom line for this course: build the skill first. AI tools built into editors (Copilot, Claude Code, Cursor, etc.) aren’t a shortcut around that – they’re worth learning to use well only after you can already do the underlying work yourself.
Privacy matters#
It’s important to exercise caution when sharing personal or sensitive information with commercial AI models like ChatGPT, Claude, or any similar tool. 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.
As discussed earlier, refer to the University’s guidelines for the safe use of AI tools and chatbots, and use the AI services recommended by your institution.
Conclusion#
AI tools can write code that looks plausible and often runs. But as the examples above show, it’s frequently wrong in ways you need real understanding to catch. As a first-time coder, that’s a good reason to be cautious, not a good reason to lean on it.
Keep these in mind:
Your goal right now is to learn to code, not to learn to prompt. Do the work yourself.
If you do use AI-generated code, test it against inputs where you already know the correct answer – don’t assume it’s right.
Read and understand the code before you use it. If you can’t explain it, you shouldn’t submit it.
Watch for confident-but-wrong answers. AI text sounds equally sure of itself whether it’s right or not.
You are responsible for the code you submit, mistakes included.