【问题标题】:Program stops after input输入后程序停止
【发布时间】:2025-04-17 03:50:02
【问题描述】:

我正在使用 openweather api 来获取当前天气。我可以让它使用此代码显示天气数据。 (格式化的api代码出来)

import requests

def current_weather():
    city_name = ('Houston')
    api_key = ('My api code')
    url = ('http://api.openweathermap.org/data/2.5/weather?q={}&appid={}').format(city_name, api_key)
    info = requests.get(url).json()
    print(info);

current_weather()

结果:

{
  'coord': {
    'lon': -95.3633,
    'lat': 29.7633
  },
  'weather': [
    {
      'id': 800,
      'main': 'Clear',
      'description': 'clear sky',
      'icon': '01d'
    }
  ],
  'base': 'stations',
  'main': {
    'temp': 295.42,
    'feels_like': 294.72,
    'temp_min': 294.14,
    'temp_max': 297.09,
    'pressure': 1024,
    'humidity': 39
  },
  'visibility': 10000,
  'wind': {
    'speed': 2.24,
    'deg': 66,
    'gust': 3.58
  },
  'clouds': {
    'all': 1
  },
  'dt': 1634495143,
  'sys': {
    'type': 2,
    'id': 2006306,
    'country': 'US',
    'sunrise': 1634473467,
    'sunset': 1634514521
  },
  'timezone': -18000,
  'id': 4699066,
  'name': 'Houston',
  'cod': 200
}
[Finished in 287ms]

但是对于城市名称,我尝试在输入中获取它,它只是询问我在哪个城市并停止程序。

def current_weather():
    city_name = input('What city are you in?: ')
    api_key = ('My api code')
    url = ('http://api.openweathermap.org/data/2.5/weather?q={}&appid={}').format(city_name, api_key)
    info = requests.get(url).json()
    print(info);

current_weather()

结果:你在哪个城市?:巴黎

没有别的了。

【问题讨论】:

  • 这可能是由infoNone 引起的。您尝试对此进行什么调试?你熟悉设置breakpoint()s 吗?这是一个很好的用例。写response = requests.get(url),在url赋值后设置断点并检查。请查看docs.python.org/3/library/pdb.html 了解更多信息。
  • 我不知道断点。我对此有点陌生,所以这是很好的信息。无论出于何种原因,崇高都没有输出任何信息。我使用了 pycharm,它起作用了。不确定是什么问题。
  • 你不需要 () 围绕字符串顺便说一句

标签: python api input openweathermap


【解决方案1】:

我自己尝试了代码,它似乎应该可以工作。 print(info) 后面好像有一个分号,在其他语言之后返回 python 时出现相关错误。

【讨论】: