[Python] Key Error 'Main' when trying an openweathermap python api tutorial

Discussão em 'Python' iniciado por Stack, Janeiro 23, 2025.

  1. Stack

    Stack Membro Participativo

    I'm currently trying to run through a tutorial of how to set up openweathermap via Python but i'm getting a KeyError and I was wondering if someone could help me out.

    The error I am getting is KeyError: 'main'

    In the actual code I have put in my API but have taken it out for obvious reasons.

    api_key = ""
    base_url = "http://api.openweathermap.org/data/2.5/weather?"

    city_name = input("Enter city name : ")

    complete_url = base_url + "appid=" + api_key + "&q=" + city_name

    response = requests.get(complete_url)

    x = response.json()

    if x["cod"] != "404":

    y = x["main"]

    current_temperature = y["temp"]
    current_pressure = y["pressure"]
    current_humidiy = y["humidity"]

    z = x["weather"]

    weather_description = z[0]["description"]

    print(" Temperature (in kelvin unit) = " +
    str(current_temperature) +
    "\n atmospheric pressure (in hPa unit) = " +
    str(current_pressure) +
    "\n humidity (in percentage) = " +
    str(current_humidiy) +
    "\n description = " +
    str(weather_description))
    else:
    print(" City Not Found ")

    Continue reading...

Compartilhe esta Página