Lab1c#

Looping and Control Statements#

Overview#

This lecture introduces looping and control statements in Python, focusing on their applications in geospatial programming. Loops and control statements are essential tools for automating repetitive tasks, making decisions based on data conditions, and efficiently processing large geospatial datasets. By mastering these concepts, you will be able to handle complex geospatial analysis tasks with greater efficiency and precision.

Learning Objectives#

By the end of this lecture, you should be able to:

  • Understand and implement for loops to iterate over sequences such as lists and tuples.

  • Use while loops to perform tasks until a specific condition is met.

  • Apply control statements (if, elif, else) to execute different blocks of code based on data conditions.

  • Combine loops and control statements to filter, process, and analyze geospatial data.

  • Develop the ability to automate repetitive geospatial tasks, making your data processing workflows more efficient.

For Loops#

For loops allow you to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each item in the sequence. This is particularly useful in geospatial programming when you need to process multiple features or coordinates.

coordinates = [
    (35.6895, 139.6917),
    (34.0522, -118.2437),
    (51.5074, -0.1278),
]  # List of tuples representing coordinates

for lat, lon in coordinates:
    print(f"Latitude: {lat}, Longitude: {lon}") 
    
# It loops through the list of coordinates.
# For each coordinate (latitude, longitude), it prints the values in the format:
# Latitude: [value], Longitude: [value].
Latitude: 35.6895, Longitude: 139.6917
Latitude: 34.0522, Longitude: -118.2437
Latitude: 51.5074, Longitude: -0.1278

Assuming you have a function to calculate distances, you can use a loop to compute distances from a reference point.

Distance Calculation (Euclidean Distance in 2D Space):

image.png

# Function Definition: this defines a Python function named calculate_distance that takes four arguments: lat1, lon1, lat2, and lon2.
def calculate_distance(lat1, lon1, lat2, lon2):
    # Placeholder for distance calculation logic
    # lat1 and lon1: Latitude and longitude of the first point.
    # lat2 and lon2: Latitude and longitude of the second point.
    return ((lat2 - lat1) ** 2 + (lon2 - lon1) ** 2) ** 0.5



reference_point = (0, 0)  # Reference point (latitude, longitude)

for lat, lon in coordinates:
    distance = calculate_distance(reference_point[0], reference_point[1], lat, lon)
    print(f"Distance from {reference_point} to ({lat}, {lon}): {distance:.2f}")
Distance from (0, 0) to (35.6895, 139.6917): 144.18
Distance from (0, 0) to (34.0522, -118.2437): 123.05
Distance from (0, 0) to (51.5074, -0.1278): 51.51

While Loops#

While loops continue to execute a block of code as long as a specified condition is true. They are useful when the number of iterations is not known beforehand, such as when processing data until a certain condition is met.

# The variable counter is initialized to 0. This will serve as a loop counter, which tracks the current position in the list of coordinates.
# The counter starts at 0 because lists in Python are zero-indexed, meaning the first element is accessed using index 0.

counter = 0
# Below is a while loop, which will continue to execute as long as the condition counter < len(coordinates) is True.

# len(coordinates) gives the total number of items (coordinates) in the list coordinates. The loop will run until counter reaches the length of the list.
while counter < len(coordinates):
    lat, lon = coordinates[counter]
    print(f"Processing coordinate: ({lat}, {lon})")
    # After processing each coordinate, the counter is increased by 1 using the counter = counter + 1 statement.
    counter = counter + 1
    
# In essence, the loop will iterate through all the items in the coordinates list.
Processing coordinate: (35.6895, 139.6917)
Processing coordinate: (34.0522, -118.2437)
Processing coordinate: (51.5074, -0.1278)

Control Statements: if, elif, else#

Control statements allow you to execute different blocks of code based on certain conditions. In geospatial programming, this is useful for handling different types of data or conditions.

elif in Python stands for “else if.” It is used in conditional statements when you want to check multiple conditions, one after another. It allows you to specify a new condition to test if the previous condition (if) was false.

if statement: The first condition is checked.

elif statement(s): If the if condition is false, Python checks the elif condition.

else statement: If none of the if or elif conditions are true, the else block is executed.

coordinates = [
    (35.6895, 139.6917),  # Tokyo
    (-34.6037, -58.3816),  # Buenos Aires
    (0.0, -77.0369)  # Equator (somewhere near)
]

for lat, lon in coordinates:
    if lat > 0:
        print(f"{lat} is in the Northern Hemisphere")
    elif lat < 0:
        print(f"{lat} is in the Southern Hemisphere")
    else:
        print(f"{lat} is near the equator")
35.6895 is in the Northern Hemisphere
-34.6037 is in the Southern Hemisphere
0.0 is near the equator

You can further categorize based on longitude:

for lat, lon in coordinates:
    if lat > 0:
        hemisphere = "Northern"
    else:
        hemisphere = "Southern"

    if lon > 0:
        direction = "Eastern"
    else:
        direction = "Western"

    print(
        f"The coordinate ({lat}, {lon}) is in the {hemisphere} Hemisphere and {direction} Hemisphere."
    )
The coordinate (35.6895, 139.6917) is in the Northern Hemisphere and Eastern Hemisphere.
The coordinate (-34.6037, -58.3816) is in the Southern Hemisphere and Western Hemisphere.
The coordinate (0.0, -77.0369) is in the Southern Hemisphere and Western Hemisphere.

Combining Loops and Control Statements#

You can combine loops and control statements to perform more complex operations, such as filtering data or applying conditions during iteration.

# Creating an Empty List (filtered_coordinates):
# The purpose of this list is to store only the coordinates that meet a certain condition (in this case, coordinates with positive longitudes).
filtered_coordinates = []

# During each iteration, the loop assigns the latitude (lat) and longitude (lon) from each tuple to the respective variables.
for lat, lon in coordinates:
    if lon > 0:
        # If the condition is true, meaning the longitude is positive, the code inside the if block is executed.
        filtered_coordinates.append((lat, lon))
print(f"Filtered coordinates (only with positive longitude): {filtered_coordinates}")
Filtered coordinates (only with positive longitude): [(35.6895, 139.6917)]
coordinates = [
    (35.6895, 139.6917),  # Tokyo (Northern Hemisphere)
    (-34.6037, -58.3816),  # Buenos Aires (Southern Hemisphere)
    (51.5074, -0.1278),    # London (Northern Hemisphere)
    (-33.9249, 18.4241)    # Cape Town (Southern Hemisphere)
]

# This line initializes a variable called southern_count and sets its value to 0. 
# This variable will be used to keep track of how many coordinates are located in the Southern Hemisphere.
southern_count = 0
for lat, lon in coordinates:
    if lat < 0:
        southern_count = southern_count + 1
print(f"Number of coordinates in the Southern Hemisphere: {southern_count}")
Number of coordinates in the Southern Hemisphere: 2

Homework 2 due by 09/08/2024#

  1. Create a list of cities with their coordinates. Write a for loop to print out only the cities that are in the Northern Hemisphere.

  2. Write a while loop that continues to print the coordinates in a list until a coordinate with a latitude less than 0 is found.

  3. Combine a for loop and if statements to count how many coordinates in a list are located in the Southern Hemisphere.

Summary#

Loops and control statements are fundamental tools in geospatial programming. They allow you to process and analyze geographic data efficiently by automating repetitive tasks and applying logic based on data conditions. Practice these concepts by applying them to your geospatial datasets and analyses.