如何基于Python中的特定用户输入循环条件语句?

时间:2015-03-10 19:47:42

标签: python

例如,在此示例代码中,

greeting = input("What's your favorite cheese?")
if greeting == "cheddar":
    print("Mine too!")

elif greeting == "bleu cheese":
    print("Gross!")

elif greeting == "parmesan":
    print("Delicious!")

else:
    cheese = input("That's not a cheese, try again!")
    cheese == greeting

如果我输入“Mozzarella”作为“问候”,我希望它能提示我“那不是奶酪”,还让我重新输入“问候”的价值,直到切达奶酪,蓝莓奶酪或巴马干酪为止。进入,如果这是有道理的。我有一个更大的程序,我正在为类工作,涉及嵌套在彼此之间的多个条件语句,并且对于每个'set'语句,我希望能够在用户输入无效条目时允许打印错误消息并允许他们再试一次而不必重新启动程序。

3 个答案:

答案 0 :(得分:3)

greeting = ''
while greeting not in ['cheddar', 'blue cheese', 'parmesan']:
    greeting = input("That's not a cheese, try again!")

答案 1 :(得分:3)

尝试以下

greeting = input("What's your favorite cheese?") #Get input
while greeting not in ['cheddar', 'blue cheese', 'parmesan']: #Check to see if the input is not a cheese
    greeting = input("That's not a cheese, try again!")
else: #If it is a cheese, proceed
    if greeting == "cheddar":
        print("Mine too!")

    elif greeting == "bleu cheese":
        print("Gross!")

    elif greeting == "parmesan":
        print("Delicious!")

    else:
        cheese = input("That's not a cheese, try again!")

What's your favorite cheese? peanut butter
That's not a cheese, try again! ketchup
That's not a cheese, try again! parmesan
Delicious!

答案 2 :(得分:2)

用每个奶酪的回复建立一个dict,并以奶酪的名称作为关键。 使用while循环。

cheeses = {'bleu cheese':'Gross!','cheddar':'Mine Too!','parmesan':'Delicous!'}

greeting = input("What's your favorite cheese?")

while greeting not in cheeses:
    print "That's not a Cheese! Try Again!"
    greeting = input("Whats your favorite cheese?")


print cheeses[greeting]