如何在天气API(Python)中使用条件语句

How to use conditional statement in weather API (Python)

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')

我正在使用 OpenWeatherMap api,我试图做一个条件语句,例如,如果温度 < 90: print('hello'),但是控制台给了我一个空的响应。

您的 temp 变量是一个字符串,因此您需要在比较之前将其转换为数字。

除非我弄错了,否则你不需要遍历你的字符串(如果我错了请提供你的 data 这样我就可以理解你期望的类型)

编辑:

我用 openweathermap 数据样本编辑了示例。

据我所知,“temp”是以数字形式给出的,因此您无需更改类型。

这个很简单,如果你没有得到预期的结果,可能只是你没有通过你的条件。

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()