首页 > 解决方案 > 在pyowm中找不到城市时如何创建输出?

问题描述

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

默认输出是错误代码:

raise exceptions.NotFoundError('Unable to find the resource') pyowm.commons.exceptions.NotFoundError: Unable to find the resource

我希望输出类似于:

抱歉,我找不到您搜索的城市。请再试一次...

到目前为止,这是我的代码:

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')))

标签: pythonpython-3.xopenweathermap

解决方案


尝试异常处理!继承自 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...')

推荐阅读