【问题标题】:How to create an output when city isn't found in pyowm?在pyowm中找不到城市时如何创建输出?
【发布时间】:2021-09-25 12:37:36
【问题描述】:

如果找不到国家/地区(例如,用户写错了城市),如何在终端上创建自定义输出?

默认输出是错误码:

raise exceptions.NotFoundError('无法找到资源') pyowm.commons.exceptions.NotFoundError: 找不到资源

我希望输出类似于:

抱歉,我无法找到您搜索的城市。 请重试...

这是我目前的代码:

import pyowm

owm = pyowm.OWM('api code')
weather = True

while weather == True:
            weather_input = input('Enter the name of the city you want me to search - ')
            mgr = owm.weather_manager()
            weather_city1 = mgr.weather_at_place(weather_input)
            w = weather_city1.weather
            print('Weather in ' + weather_input + ' - ' + str(w.temperature('celsius')))

【问题讨论】:

  • 试试try:\n 'your whole code goes here' \nexcept pyowm.commons.exceptions.NotFoundError: print('Sorry, I was unable to find the city you searched for. Please try again...')

标签: python python-3.x openweathermap


【解决方案1】:

尝试异常处理!继承自 C 派生语言的一个不错的 Python 特性:

from pyowm import OWM
from pyowm.commons.exceptions import NotFoundError

owm = OWM('api code')
mgr = owm.weather_manager()

while True:
            weather_input = input('Enter the name of the city you want me to search - ')
            try:
                weather_city1 = mgr.weather_at_place(weather_input)
                w = weather_city1.weather
                print('Weather in ' + weather_input + ' - ' + str(w.temperature('celsius')))
            except NotFoundError:
                print('Sorry, I was unable to find the city you searched for. Please try again...')

【讨论】:

    猜你喜欢
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 2019-03-12
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多