Your First Python Script (No Installation Required)

Before You Start

You should know: - How to open a web browser.

You will learn: - What Python code looks like and how to read it. - How to work with variables, numbers, text, and lists. - How to use if statements and loops β€” the building blocks of geographic models. - That code is just a sequence of readable instructions.


1. Zero Installation Required

The hardest part of learning to code is often not the code itself β€” it is getting an environment installed and configured. We will do that properly in later chapters, but for now we want to feel what it is like to actually command a computer.

Use an online Python interpreter. Open your browser and go to one of these:

All three options execute real Python without you installing anything. The code you type runs on a computer somewhere in the cloud and sends the result back to your screen.

2. Your First Instruction

Python reads your code from top to bottom, one line at a time, and executes each instruction as it goes. Let’s start with the most immediately visible action: printing text to the screen.

print("Hello, computational geography!")

Type this into your interpreter and press Enter (or click Run). The computer will output:

Hello, computational geography!

You just wrote code. print() is a function β€” a named action that Python knows how to perform. The text inside the parentheses is the argument you are passing to it.

3. Variables: Giving Names to Values

Geography is full of numbers β€” elevations, temperatures, coordinates, population counts. Instead of typing the same number over and over, we store values in variables.

# Lines beginning with # are comments. Python ignores them.
# Use comments to explain what your code is doing.

elevation_base = 1500   # metres
elevation_peak = 3200   # metres

elevation_change = elevation_peak - elevation_base

print("Elevation gain:", elevation_change, "metres")

Run this. Python remembers both numbers, performs the subtraction, and assembles the output from parts. The result should be Elevation gain: 1700 metres.

Variable names can be almost anything, but use short, descriptive names. elevation_base is better than x. Python variable names cannot contain spaces β€” use underscores instead.

4. Types of Data

Python handles several kinds of data:

# Integers (whole numbers)
num_samples = 250

# Floats (decimal numbers)
latitude = 51.5074

# Strings (text, always wrapped in quotes)
city_name = "London"

# Booleans (True or False β€” exactly those words, capital first letter)
is_coastal = True

# You can print any of them
print(city_name, "is at latitude", latitude)
print("Coastal city:", is_coastal)

The type of a variable matters. You can do arithmetic on numbers. You can’t do arithmetic on text (unless you’re combining strings, which uses +). Python will tell you if you mix them incorrectly.

5. Lists: Storing Multiple Values

A single variable holds one value. A list holds many values in order.

# A list of elevation measurements along a transect
elevations = [120, 340, 580, 720, 690, 440, 210]

print("First measurement:", elevations[0])   # Python counts from 0
print("Last measurement:", elevations[-1])   # -1 means "the last one"
print("Number of measurements:", len(elevations))

Lists are one of the most important structures in geographic computing. A raster layer is essentially a list of lists (a grid of values). A route is a list of coordinates. A shapefile attribute table is a list of records.

6. Logic: Making Decisions

The power of code comes from its ability to apply rules consistently across data. The if statement lets you define conditional logic:

temperature = -5  # degrees Celsius

if temperature < 0:
    print("Precipitation will fall as snow.")
elif temperature < 10:
    print("Cold rain likely.")
else:
    print("Liquid precipitation.")

Notice the indentation: the lines underneath if, elif, and else are indented by four spaces (or one Tab). Python uses indentation to understand which lines belong to which block. If you forget to indent, Python will complain.

Change the value of temperature and re-run to test each branch.

7. Loops: Doing the Same Thing Many Times

This is where the difference between GIS and scientific computing becomes concrete.

# Five elevation readings along a valley transect
elevations = [120, 340, 580, 720, 690]

for elevation in elevations:
    if elevation > 500:
        print(elevation, "m β€” above treeline")
    else:
        print(elevation, "m β€” below treeline")

A for loop steps through every item in a list, one at a time, and runs the indented block for each one. In this example it processes 5 values; the code would look identical for 5 million values β€” the computer just keeps going.

This is the pattern behind nearly every geographic computation: take a dataset, loop through it, apply a rule to each record, output a result.

8. From Scripts to Programs

What you just wrote is called a script β€” a text file of instructions that run top to bottom. Everything in this chapter ran in the cloud, in someone else’s computer. That is fine for practice.

Eventually, you want Python running on your own machine, reading your own files β€” a satellite image you downloaded, a CSV of field measurements, a shapefile of census boundaries β€” and writing results back to your own folders.

To do that, you need Python installed locally, and you need to understand how your computer organizes files. The next chapter covers exactly that.

Verify Your Work

Before moving on, confirm you can do each of these in your online interpreter:

If any of these stumped you, re-read the relevant section. The rest of this book assumes these ideas are familiar.

Next Steps

Before installing Python on your machine, you need to understand how your computer organizes files without a graphical window. That is the command line.