【问题标题】:python import location from one def to another def to print location from weather APIpython将位置从一个def导入另一个def以从天气API打印位置
【发布时间】:2020-09-23 14:29:45
【问题描述】:
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)没有定义我可以做些什么来解决这个问题?

【问题讨论】:

    标签: python api tkinter location weather


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      location(stad)没有定义,因为“location”是一个不接收参数的函数。

      你必须写: city = location(),然后在函数“location”中计算的变量“stad”将分配给您的变量“city”。清楚了吗?

      另外,一行:

      location(stad)
      

      (函数开头get_weather()) 看起来像不必要的线。如果不使用返回的内容,为什么要调用该函数?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-07
        • 2014-11-25
        • 1970-01-01
        相关资源
        最近更新 更多