使用While循环检查用户的输入(字符串)是否属于列表?

时间:2019-01-17 19:44:56

标签: python python-3.x input while-loop

我是Python的新手,有一定的C语言背景。我想用try设置while循环-除了-else结构。当尝试验证数据类型时(使用ValueError除外),例如提示用户输入整数,我已经成功完成了此操作。但是,对于此程序,用户输入了一个字符串,程序需要根据字符串列表检查该字符串,如果不在列表中,请再次询问用户。到目前为止,我的代码可以运行,但是无论用户输入如何,循环都会中断。现在是这里:

senses = ["touch", "smell", "sight", "hearing", "taste"]


while True:
    try:
        choice = input("What is your favorite sense? ")

    except: 
        if choice not in senses:
            print("Sorry, I don't think that's a sense")
            #try again, return to start of loop
            continue 
    else:
        break 

最初我的代码看起来像这样并且可以正常工作,但是输入法存在冗余的问题:

senses = ["touch", "smell", "sight", "hearing", "taste"]
choice = input("What is your favorite of the 5 human senses:")

while choice not in senses:

    choice =input("What is your favorite of the 5 human senses")

2 个答案:

答案 0 :(得分:1)

关于个人喜好/问题的适合性,但是我倾向于使用类似的东西

senses = ["touch", "smell", "sight", "hearing", "taste"]
choice = ""

while choice not in senses:
    choice =input("What is your favorite of the 5 human senses")

这会将choice初始化为senses中没有的内容,从而强制执行第一个循环

答案 1 :(得分:1)

我会这样写:

this::hashCode

这样,您只在一个地方问问题。 senses = {"touch", "smell", "sight", "hearing", "taste"} while True: choice = input("What is your favorite of the 5 human senses? ") if choice in senses: break 的意思是“永远做这件事”,一旦满足条件,while True就会停止循环。