如何解决python中的input()问题?

怒狼

我正在python上创建我的第一个程序。目的是获得旅行成本的输出。在下面的代码中,我希望python引发错误并询问用户是否重试输入是否不是字典的一部分。

我尝试使用True时使用,但使用代码时确实使我重试了错误的输入,但没有引发提示用户的错误。

c = {"Charlotte": 183, "Tampa": 220, "Pittsburgh": 222, "Los Angeles": 47}

def plane_ride_cost():
    city = ''
    while True:
        city = input("Name of the city: ")
        if  city in c.keys():
            return c[city]
            break
    else:
        print ("Invalid input please try again")

plane_ride_cost()

Output:
Name of the city: Hyderabad
Name of the city: 

如果您注意到它需要输入,然后要求我在没有提示的情况下重试。

奶奶疼

本着易于获得宽恕而不是获得许可的精神,另一种解决方案是

def plane_ride_cost():
    while True:
        city = input("Name of the city: ")
        try:
            return c[city]
            break
        except KeyError:
            print ("Invalid input please try again")

plane_ride_cost()

try 块尝试仅执行该行,而不检查输入是否正确。

如果有效,except则跳过块。

如果有一个KeyError,如果密钥city中不存在c,则会发生,它将捕获except不会导致程序崩溃,而是except执行块中的行。

您可以具有多个`except块,以捕获不同的异常。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章