首页 > 解决方案 > python将位置从一个def导入另一个def以从天气API打印位置

问题描述

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() 获取我的 from city = location(stad) ((stad 表示荷兰语中的城市))

但它不起作用 python 说位置(stad)没有定义我能做些什么来解决这个问题?

标签: pythonapitkinterlocationweather

解决方案


您错误地处理了函数响应。您没有将响应分配给变量,而是将参数(未定义变量)传递给函数“location”。

而不是location(stad),您必须使用stad = location().

此外,我在您的代码中看到的一些内容可能是不必要的 -
在“位置”定义中,由于您只返回城市(stad),因此您不必处理经度和纬度。此外,由于经度/纬度可以是小数,如果使用“句点”( ) 进行拆分,您可能无法获得准确的值.


推荐阅读