Gentle Introduction to Programming Part 1

: for GIS Dummies

Hyesop Shin

University of Auckland

May 7, 2025

What will we cover?

  • Why programme in a GIS course?
  • Programming Basics
  • Interactive lecture

Why do we learn to code?

  • We are not computer scientists (I am not at least)
  • GISci and Geography disciplines are becoming increasingly quantitative
  • Large datasets
  • We want to do our job quickly and do less of the same work.
  • Programming can also be fun
  • Programming can help make us better scientists - Open Science

Example: Python

What is a computer?

What is a computer - Python

What are computers good at?

Tasks computers are good at include 1:

  • Well-defined tasks (i.e. Clear aim, Low Risk of Failure)
  • Data storage and manipulation
  • Repetitive calculations
  • Processing data or instructions (Important!)

What are computers bad at?

  1. Abstract or poorly defined tasks
print("Python" > "R")
False
print("Ronaldo" > "Messi")
True
  1. Tasks requiring impossible computing power (intractable tasks)
## True Pi
3.14159265358979323846264338327


>>> from mpmath import mp
>>> mp.dps = 20    # set number of digits
>>> print(mp.pi)
3.1415926535897932385
  1. Can’t remember what you’ve written (unless you wrote it down somewhere)

We need to be less poetic

and become more direct to the point

Why Python?

1. Python is widely used

  • Python being 1st in a row in programming (TIOBE Rank)

2. Python is open

  • Open as in
    • free of charge
    • as in access (download and run)
    • over time
    • not closed
    • reuse and change
    • any place (platform) and for everyone

3. Python is approachable

  • Modern interpreted languages (Python) – Code is interpreted line-by-line via a programme
  • Translating high-level human readable code to machine readable code
  • Scripting
    • Only need snippets of code
    • Can perform jobs quickly
    • Ideal for GIS jobs

4. Python is connected

  • Geographic Information Systems (GIS) software such as QGIS or ArcGIS now include a Python interpreter built in to the software
  • Can customise solutions for your specific data analysis needs

5. Python is linked to our GISCI courses & future jobs

  • ENVSCI 203 Modelling Environmental Systems
  • GISCI 341 Advanced Remote Sensing
  • GISCI 343 GIScience Programming and Development
  • Honours and Postgraduate courses

Industry & Academia & Public Sector…

The War of Coding

FYI: We have plenty of Geocomputation courses in postgraduate courses!
R & Python both have specialties.
FYI: I am an R enthusiast

Interactive Lecture using Python

What we will cover:

  • Basics
  • Variables
  • Loops and basic conditionals
  • Functions
  • Geopandas

How will we cover it?

  • Install Python on your machine
  • Jupyter lab / Notebook
  • Google Colab

    • “Another” Free service provided by Google
    • Live code, text and graphics in one place
    • Compatible with multiple languages

 

Roll your sleeves and let’s get started!

 

Make sure you are well set up with Google Colab using the URL below:
https://colab.research.google.com

 

I will code here: https://tinyurl.com/gisci242

Basic Programming Concepts

We will cover:

  • Simple Python maths
  • Functions
  • for loops
  • Conditional Statements
  • Import files

Simple Python maths

1 + 1

5 * 7

2**3

10 % 2

Simple Python maths - answers

1 + 1
2
5 * 7
35
2**3
8

Strings

print("hello world") # print strings

len("hello world") # to count text in Python Shell
print(len("hello world")) # in Google Colab

Maths with modules

sin(3)
sqrt(4)

 
 

Did you get the result you expected?

Facing Errors can be daunting

sin(3)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-acdde95a6016> in <cell line: 1>()
----> 1 sin(3)
NameError: name 'sin' is not defined
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-317e033d29d5> in <cell line: 1>()
----> 1 sqrt(4)

NameError: name 'sqrt' is not defined

 

Python can’t calculate square roots or do basic stats?
Of course it can, but we need one more step.

Solution

import math

math.sin(3)
math.sqrt(4)

 

Well done! You have just managed to use a math module too!

Combining Functions

Functions can also be combined. The print() function returns values within the parentheses as text on the screen. Let’s print the value of the square root of four.

print(math.sqrt(4))
print("The square root of 4 is", math.sqrt(4))

Variables

A variable can be used to store values calculated in expressions and used for other calculations

temp_celsius = 10.0

print(temp_celsius)
10.0

Data types

  • A data type determines the characteristics of data in a programme
  • Basic data types in Python.
Data type name Data type Example
int Whole integer values 4
float Decimal values 3.1415
str Character strings ‘Freezing’
bool True/false values True

Data types

weatherForecast = "Freezing"
type(weatherForecast)
<class 'str'>

Your Turn!

  • Print the type() of:
- 33
- 8.394
- Windy
- False

Lists

When we have more clothes/items we would like to align similar types of clothes into a drawer

List Example 1

top = ["socks", "underwear", "handkerchief"]
middle = ["T-shirts", "Pajamas", "Trousers", "Shorts"]
bottom = [30, 73, 100, 62]

 

print(top[0])
print(min(bottom))
socks  # <- index "an element of a list"
30     # <- the smallest element of the list

List Example 2

Let’s first create a list of selected station_name values and print it to the screen.

station_names = [
    "Britomart",
    "Ōrākei",
    "Meadowbank",
    "Purewa",
    "Glen Innes",
    "Tamaki",
    "Panmure",
    "Sylvia Park"
]

station_names
['Britomart', 'Ōrākei', 'Meadowbank', 'Purewa', 'Glen Innes', 'Tamaki', 'Panmure', 'Sylvia Park']
type(station_names)
<class 'list'>

Index values

To access an individual value in the list we need to use an index value.

station_names[1]
'Ōrākei'

Python returns ‘Ōrākei’ instead of ‘Britomart’. Can anybody guess why?

Index values

station_names[2]
'Meadowbank'
station_names[2:5]
['Meadowbank', 'Purewa', 'Glen Innes']
station_names[-1]
'Sylvia Park'
station_names[-8]
'Britomart'

Modifying list values

station_names[-1] = 'Shopping Mall'
station_names
['Britomart', 'Ōrākei', 'Meadowbank', 'Purewa', 'Glen Innes', 'Tamaki', 'Panmure', 'Shopping Mall']

Modifying list values

station_names[-1] = 'Shopping Mall'
station_names
['Britomart', 'Ōrākei', 'Meadowbank', 'Purewa', 'Glen Innes', 'Tamaki', 'Panmure', 'Shopping Mall']
station_names.reverse()
station_names
['Shopping Mall', 'Panmure', 'Tamaki', 'Glen Innes', 'Purewa', 'Meadowbank', 'Ōrākei', 'Britomart']

Modifying list values

station_names.append("new station")
print(station_names)
['Shopping Mall', 'Panmure', 'Tamaki', 'Glen Innes', 'Purewa', 'Meadowbank', 'Ōrākei', 'Britomart', 'new station']

Your Turn!

  1. Define station_names in your environment
  2. Add Otahuhu, Middlemore, Papatoetoe, Puhinui, Manukau as a list (you can Google “Auckland Eastern Line” and find the Wikipedia)
  3. Assign that in your environment as more_eastern
  4. This time, try extend to combine the two lists
station_names = ["Britomart", "Ōrākei", "Meadowbank", "Purewa", 
  "Glen Innes", "Tamaki", "Panmure", "Sylvia Park"]

Documentation

  • At this point, you might think, Hang on, do I have to memorise everything?
  • The answer is NO
  • If you are stuck, visit https://www.python.org/doc
  • Google your problem (Stackoverflow)
  • ChatGPT and Gemini (🧐)

for loop

  • Loops allow parts of code to be repeated some number of times
  • Iterates over all of the items in a Python list and performing a calculation on each item.

vs

for loop: concept

 

for variable in collection:
    do things with variable

Let’s break down the code above to see some essential aspect of for loops:

  • The variable can be any name you like.
  • The statement of the for loop must end with a colon (:)
  • The code that should be executed as part of the loop must be indented beneath the for loop statement.
  • The typical indentation is 4 spaces.
  • There is no additional special word needed to end the loop, you simply change the indentation back to normal.

Your daily for loop

for day in my_life:
    wake_up()
    take_shower()
    eat_breakfast()
    brush_teeth()
    ride_beam()
    come_to_lecture()
    ...

for loop: an example

for name in station_names:
    print(name)
Britomart
Ōrākei
Meadowbank
Purewa
Glen Innes
Tamaki
Panmure
Sylvia Park

Different example

european_cities = ["Amsterdam", "Brussels", "London", "Rome"]

for city in european_cities:
    print(city)

Examples using range

for value in range(5):
    print(value)
0
1
2
3
4

Examples using range

group1 = [1, 3, 5]
group2 = [0, 1, 2]

for i in range(2):
    print(group1[i], group2[i])
1 0
3 1

Your Turn!

cities = ["Helsinki", "Stockholm", "Oslo", "Reykjavik", "Copenhagen"]
countries = ["Finland", "Sweden", "Norway", "Iceland", "Denmark"]
  • The indices of the cities and countries are in the same order
  • For example, Helsinki and Finland are in index 0
  • Create a for loop that describes something like Helsinki is the capital of Finland

Examples using two lists - Answers

for i in range(5):
    print(cities[i], "is the capital of", countries[i])
    
for i in range(len(cities)):
    print(cities[i], "is the capital of", countries[i])

 

Helsinki is the capital of Finland
Stockholm is the capital of Sweden
Oslo is the capital of Norway
Reykjavik is the capital of Iceland
Copenhagen is the capital of Denmark

Conditional statements

  • We will learn how to make choices in our code using conditional statements (if, else) and Boolean values (True, False).
  • Conditional statements can change the code behaviour based on certain conditions.
  • The idea is simple: IF a condition is met, THEN a set of actions is performed.

if else Example 1

temperature = 17

if temperature > 25:
    print("it is hot!")
else:
    print("it is not hot!")
    
print(temperature)    
it is not hot

if else Example 2

temperature = 30

if temperature > 25:
    print("it is hot!")
else:
    print("it is not hot!")
    
print(temperature)    
it is hot

if statement without else

  • The code indented under the if-statement is not executed if the condition is not True. Instead, code under the else-statement gets executed.
  • How about if without else?
temperature = 17

if temperature > 25:
    print(temperature, "is greater than 25")

Conditional operator

weather = "rain"

if weather == "rain":
    print("Wear a raincoat!")
else:
    print("No raincoat needed.")
Wear a raincoat!

Comparison operators

Operator Description
< Less than
<= Less than or equal to
== Equal to
>= Greater than or equal to
> Greater than
!= Not equal to

Boolean values

  • Comparison operations yield Boolean values (True or False).
  • In Python, the words True and False are reserved for these Boolean values, and can’t be used for anything else.
temperature > 25
False

Combinations

Combining conditions

  • We can also use and and or to combine multiple conditions on boolean values
Keyword Example Description
and a and b True if both a and b are True
or a or b True if either a or b is True

Combination Example

weather = "rain"
wind_speed = 14
comfort_limit = 10

# If it is windy or raining, print "stay at home",
# otherwise (else) print "go out and enjoy the weather!"
if (weather == "rain") or (wind_speed >= comfort_limit):
    print("Just stay at home")
else:
    print("Go out and enjoy the weather! :)")
Just stay at home

Combining for-loops and conditional statements

  • We can also combine for-loops and conditional statements.
  • Let’s iterate over a list of temperatures, and check if the temperature is hot or not
temperatures = [0, 12, 17, 28, 30]

# For each temperature, if the temperature is greater than 25, print "..is hot"
for temperature in temperatures:
    if temperature > 25:
        print(temperature, "is hot")
    else:
        print(temperature, "is not hot")
0 is not hot
12 is not hot
17 is not hot
28 is hot
30 is hot

Summary - What have we learned?

  • Programming is not too difficult than you think. They are easy to understand and share (and fun!)
  • Programmes keep a log of the changes you make to your programmes - open science
  • Python is one of the popular programming languages - we are going to nail this!
  • Basics of Python
    • Basic programming
    • Functions
    • for loops
    • Conditional statements
    • Combos of the above

Next week

  • How to import spreadsheet data
  • How to clean and use data
  • Learn it through Pandas module

References

  • Tekanen et al. (2022), Introduction to Python for Geographic Data Analysis, https://pythongis.org/
  • Rey et al. (2020), Geographic Data Science with Python, https://geographicdata.science/book
  • Dorman et al (2023), Geocomputation with Python, https://py.geocompx.org/

Thanks!
Q & A