Home > Blockchain >  How to use conditional statement in weather API (Python)
How to use conditional statement in weather API (Python)

Time:03-30

appid = ''
city = ''
URL = f'https://api.openweathermap.org/data/2.5/weather?q=={city}&appid={appid}'

r = requests.get(URL)
res = r.json()

data = res

def check():
temp = "{0:.2f}".format(data["main"]["temp"])
for item in temp:
if item < 90:
print('hello')

I am using OpenWeatherMap api, I tried to make a conditional statement, for example, if the temperature < 90: print('hello'), but the console gave me an empty response.

CodePudding user response:

your temp variable is a string so you need to convert it to a number before compare it.

And unless I got it wrong, you don't need to loop over your string (If I'm wrong please provide your data so I can understand what type you are expecting)

Edit:

I edited my example with an openweathermap data sample.

From what I see, the "temp" is given as a number so you don't need to change the type.

This is very simple, if you don't get the expected result it might just be related to the fact you don't pass your condition.

data_example = {
    "id":88319,
    "dt":1345284000,
    "name":"Benghazi",
    "coord":{"lat":32.12,"lon":20.07},
    "main":{"temp":85.15,"pressure":1013,"humidity":44,
    "temp_min":306,"temp_max":306},
    "wind":{"speed":1,"deg":-7},
    "weather":[
        {"id":520,"main":"rain","description":"light intensity 
        shower rain","icon":"09d"},
        {"id":500,"main":"rain","description":"light rain","icon":
        "10d"},
        {"id":701,"main":"mist","description":"mist","icon":"50d"}
              ],
    "clouds":{"all":90},
    "rain":{"3h":3}
}

def check():
    # temp = "{0:.2f}".format(example_data["main"]["temp"]) # you don't need this
    temp = example_data["main"]["temp"]
    if temp < 90:
        print("temp is below 90", temp)
    else:
        print("temp is beyond 90", temp)

check()
  • Related