如何正确处理错误 python

How to error handle properly python

我知道解决方案离这里不远,但我正在努力实现根据用户输入为地图比例分配数值的能力。该代码是非常自我解释的,但我希望用户从 4 种缩放状态中选择,使用输入 return 我的地图的数值作为缩放起点。

zoom=5
while True:
    where = raw_input('Where would you like a map of?')
    try:
        heatmap = folium.Map(location=geo(where), tiles='Stamen Toner', zoom_start=zoom)
        pointmap = folium.Map(location=geo(where), tiles='Stamen Toner', zoom_start=zoom)
    except AttributeError, GeocoderServiceError:
        print "Cannot create map with the given location. Please try again."
    else:
        break
while True:
    zoom_state = ['city', 'state', 'country', 'world']
    zoom_state= raw_input('What level of detail would you like: city, state, country, or world?')
    try:
         for response in zoom_state:
            if response is ['city']:
                zoom == 9
                if response is ['state']:
                    zoom == 7
                    if response is ['country']:
                        zoom == 5
                        if response is ['world']:
                            zoom == 9 
    except TypeError, IndexError:
        print 'Please enter: city, state, country, or world. Try again'
        continue
    else:
        break

heatmap = folium.Map(location=geo(where), tiles='Stamen Toner', zoom_start=zoom)
pointmap = folium.Map(location=geo(where), tiles='Stamen Toner', zoom_start=zoom)

现在我可以为 zoom_state 放入任何东西,它会 运行。

提前致谢!

您可能正在寻找这样的东西:

zoom=5
while True:
    where = raw_input('Where would you like a map of?')
    try:
        heatmap = folium.Map(location=geo(where), tiles='Stamen Toner', zoom_start=zoom)
        pointmap = folium.Map(location=geo(where), tiles='Stamen Toner', zoom_start=zoom)
    except AttributeError, GeocoderServiceError:
        print "Cannot create map with the given location. Please try again."
    else:
        break
while True:
    zoom_level = {'city':9, 'state':7, 'country':5, 'world':9}
    zoom_detail = raw_input('What level of detail would you like: city, state, country, or world?')
    try:
         zoom = zoom_level[str(zoom_detail)]
    except TypeError, IndexError:
        print 'Please enter: city, state, country, or world. Try again'
        continue
    else:
        break

heatmap = folium.Map(location=geo(where), tiles='Stamen Toner', zoom_start=zoom)
pointmap = folium.Map(location=geo(where), tiles='Stamen Toner', zoom_start=zoom)