python - 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)没有定义我能做些什么来解决这个问题?
解决方案
您错误地处理了函数响应。您没有将响应分配给变量,而是将参数(未定义变量)传递给函数“location”。
而不是location(stad)
,您必须使用stad = location()
.
此外,我在您的代码中看到的一些内容可能是不必要的 -
在“位置”定义中,由于您只返回城市(stad),因此您不必处理经度和纬度。此外,由于经度/纬度可以是小数,如果使用“句点”( ) 进行拆分,您可能无法获得准确的值.
。
推荐阅读
- excel - 我是否缺少声明或工作表对象标题?
- python - 扭曲 - 在线程中运行
- python - 当条目小部件没有聚焦时,我将如何隐藏列表框小部件?
- css - Font Awesome(在 Chrome 中)的三个警告,即“完整性不匹配”、“适当的 `as` 值”和“请求凭据不匹配”
- hadoop - 检索使用 hadoop distcp 复制的数据大小
- objective-c - 如何处理同时触发的多个警报
- python - 如何使用约束启动 numpy 数组
- c++ - 未分配默认字段初始化的值
- typescript - 如何在 vue.config.js 中添加 source-map-loader
- entity-framework - 带有 ef 核心的 Linq