问题描述
def location():
res = requests.get('https://ipinfo.io/')
data = res.json()
stad = data['city']
location = data['loc'].split('.')
latitude = location[0]
longitude = location[1]
return stad
def get_weather():
location(stad)
weather_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
url = 'https://api.openweathermap.org/data/2.5/weather'
# q=Amsterdam&appid=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
city = location(stad)
params = {'q': city,'APPID': weather_key,'units': 'metric'}
response = requests.get(url,params= params)
print(f'Het weer vandaag in Utrecht is:')
print(response.json())
尊敬的stackoverflow用户
我尝试从def location()从city = location(stad)获取我的信息((stad表示荷兰的城市))
但是它无法正常工作python表示未定义location(stad),我该怎么做才能解决此问题?
解决方法
location(stad)
未定义,因为“位置”是不接收参数的函数。
您必须写:
city = location()
,然后在函数“ location”中计算的变量“ stad”将分配给您的变量“ city”。清楚吗?
此外,该行:
location(stad)
(在函数get_weather()
的开头)
看起来像不必要的线。如果不使用返回的内容,为什么要调用该函数?
您未正确处理函数响应。您没有将响应分配给变量,而是将参数(未定义的变量)传递给了“位置”函数。
您必须使用location(stad)
来代替stad = location()
。
此外,我在您的代码中看到的一些东西可能是不必要的-
在“位置”定义中,由于仅返回城市(stad),因此无需处理经度和纬度。另外,由于经度/纬度可以是小数,因此如果使用“句点”(.
)进行分割,则可能无法获得确切的值。