Step 6 of 6

Make it yours

You built a real program. Now make it yours.

Goal for this lesson: move the forecast to a city you care about, and try a change of your own.

Step 1: Pick your location

The weather service finds places by latitude and longitude. Search for your city’s coordinates online, then change the URL in weather.py. To make this easy, replace the URL block with a function that builds it:

def forecast_url(latitude, longitude):
    return (
        "https://api.open-meteo.com/v1/forecast"
        f"?latitude={latitude}&longitude={longitude}"
        "&hourly=temperature_2m&temperature_unit=fahrenheit&forecast_days=2&timezone=auto"
    )

Then change get_forecast to take the coordinates, and use them in the main block. The finished file:

import csv

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import requests


def forecast_url(latitude, longitude):
    return (
        "https://api.open-meteo.com/v1/forecast"
        f"?latitude={latitude}&longitude={longitude}"
        "&hourly=temperature_2m&temperature_unit=fahrenheit&forecast_days=2&timezone=auto"
    )


def get_forecast(latitude=29.42, longitude=-98.49):
    response = requests.get(forecast_url(latitude, longitude), timeout=10)
    response.raise_for_status()
    return response.json()


def hourly_readings(data, count=12):
    hourly = data["hourly"]
    return list(zip(hourly["time"], hourly["temperature_2m"]))[:count]


def save_readings(readings, path="readings.csv"):
    with open(path, "w", newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["time", "temperature_f"])
        writer.writerows(readings)


def draw_chart(readings, title="Forecast", path="forecast.png"):
    hours = [time[11:16] for time, _ in readings]
    temps = [temp for _, temp in readings]
    plt.figure(figsize=(8, 4))
    plt.plot(hours, temps, marker="o")
    plt.title(title)
    plt.ylabel("Temperature (°F)")
    plt.xticks(rotation=45)
    plt.tight_layout()
    plt.savefig(path)
    plt.close()


if __name__ == "__main__":
    CITY = "Austin"
    LAT, LON = 30.27, -97.74
    readings = hourly_readings(get_forecast(LAT, LON), count=24)
    save_readings(readings)
    draw_chart(readings, title=f"24-hour forecast for {CITY}")
    print(f"Saved readings.csv and forecast.png for {CITY}")

Swap CITY, LAT and LON for your own place and run it.

Step 2: Try one change of your own

Pick one and try it:

What you’ve learned

You asked a web service for data, turned it into Python, saved it, and drew it. That is the same loop behind almost every data app out there, from weather dashboards to sports stats. Bigger projects are just more of these small steps.

Check yourself

Does your chart show your city? Then you’re done, and you built it. Well done!