如何在天气 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'),但控制台给了我一个空响应。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您的
temp
变量是一个字符串,因此您需要在比较之前将其转换为数字。,除非我错了,否则您不需要循环循环(如果我错了>编辑:
我用OpenWeathMap数据示例编辑了我的示例。
据我所知,“温度”是一个数字,因此您不需要更改类型。
这很简单,如果您没有得到预期的结果,它可能只是与您没有通过状况的事实有关。
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 yourdata
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.