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?
Abstract or poorly defined tasks
print("Python">"R")
False
print("Ronaldo">"Messi")
True
Tasks requiring impossible computing power (intractable tasks)
## True Pi3.14159265358979323846264338327>>>from mpmath import mp>>> mp.dps =20# set number of digits>>>print(mp.pi)3.1415926535897932385
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+15*72**310%2
Simple Python maths - answers
1+1
2
5*7
35
2**3
8
Strings
print("hello world") # print stringslen("hello world") # to count text in Python Shellprint(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 mathmath.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.0print(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
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 inrange(5):print(cities[i], "is the capital of", countries[i])for i inrange(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 =17if temperature >25:print("it is hot!")else:print("it is not hot!")print(temperature)
it is not hot
if else Example 2
temperature =30if 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 =17if 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 =14comfort_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")
0isnot hot12isnot hot17isnot hot28is hot30is 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/