Control flow lets your code make decisions and repeat tasks—key for any non-trivial program. In this blog post, we’ll explore:
-
If–Else Statements
-
For Loops
-
While Loops
-
Break, Continue & Loop Control
-
Common GIS Loops (e.g., processing files, features, coordinates)
Let’s dive in!
1. If–Else Statements
Use if, elif, and else to run code based on conditions:
temperature = 22
if temperature >= 30:
print("It’s hot outside!")
elif temperature <= 15:
print("It’s cold outside!")
else:
print("The weather is mild.")
Do’s:
-
Always end condition lines with a colon (
:
). -
Indent via 4 spaces consistently.
-
Use
elif
for multiple branches rather than nestedif
statements.
Don’ts:
-
Don’t compare floats for exact equality; use a tolerance check.
-
Avoid deep nesting—extract logic into functions.
2. For Loops
For loops iterate over sequences like lists, tuples, strings, or ranges:
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I love {fruit}")
# Using range()
for i in range(1, 6): # 1 through 5
print(i)
Do’s:
-
Use
range(start, stop, step)
for numeric sequences. -
Unpack tuples directly:
for x, y in point_list:
.
Don’ts:
-
Don’t modify the sequence being iterated.
-
Avoid long-running loops without vectorized alternatives in performance-critical code.
3. While Loops
While loops keep running as long as a condition is true:
count = 0
while count < 5:
print(count)
count += 1
# User input loop
cmd = ''
while cmd.lower() != 'exit':
cmd = input('Enter command (exit to stop): ')
print(f'You entered: {cmd}')
Do’s:
-
Ensure the condition will become
False
eventually. -
Use
break
to exit early when needed.
Don’ts:
-
Don’t forget to update loop variables—leads to infinite loops.
-
Avoid complex conditions inside the
while
statement; simplify beforehand.
4. Break, Continue & Loop Else
Control loop execution with:
-
break: exit the loop immediately.
-
continue: skip to the next iteration.
-
else on loops: runs if the loop finishes without
break
.
# break example
for num in range(1, 10):
if num == 5:
print('Found 5, stopping loop')
break
print(num)
# continue example
for char in 'Python':
if char == 'h':
continue # skip printing 'h'
print(char)
# for-else example
for item in []:
print('Never runs')
else:
print('Loop completed without break')
Do’s:
-
Use
break
for sentinel or error detection. -
Use
continue
to skip specific cases and keep loops readable.
Don’ts:
-
Overusing both can obscure loop logic—use sparingly.
5. Common GIS Loops
In geospatial workflows, you’ll often loop through files, GeoJSON features, or coordinate grids.
5.1 Looping Through Files
import os
folder = '/data/rasters'
for fname in os.listdir(folder):
if fname.endswith('.tif'):
path = os.path.join(folder, fname)
print(f'Processing {path}')
# raster processing logic here
5.2 Looping GeoJSON Features
import json
with open('features.geojson') as f:
gj = json.load(f)
for feat in gj['features']:
geom = feat['geometry']
props = feat['properties']
print(f"Feature {props.get('id')}: {geom['type']}")
# feature processing
5.3 Looping Coordinate Grids
# Generate grid points
grid = [(x, y) for x in range(0, 100, 10) for y in range(0, 100, 10)]
for x, y in grid:
print(f"Point: ({x}, {y})")
# grid-based analysis
Do’s:
-
Validate file types and geometry before processing.
-
Use libraries like NumPy or Pandas for large data loops.
Don’ts:
-
Hard-code paths—use variables or config files.
-
Don’t nest loops deeply; extract repeated operations into helper functions.