I am having trouble vaildating my code.I need my code to loop untill a valid answer is inputted

前端 未结 4 1077
广开言路
广开言路 2021-01-25 05:34

I am struggling with this piece of Python code. The problem is,when a user enters something wrong I need my code to keep looping until they input a valid answer. This is how the

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-25 06:12

    while True:
        choice = input("Please enter a drink from the menu above\n").lower()
    
        if choice == "1" or choice == "fanta":
            Order[DRINK] = "Fanta"
            break
        if choice == "2" or choice == "coke":
            Order[DRINK] = "Coke"
            break
        if choice == "3" or choice == "pepsi":
            Order[DRINK] = "Pepsi"
            break
        if choice == "4" or choice == "sprite":
            Order[DRINK] = "Sprite"
            break
    

    This is pretty clunky, but it's most in line with what you've already got. I'd suggesting moving most of these items into lists like this, but that's a bit of a refactor for this answer. Consider the below, but really all you have to do is stick your input into an infinite loop and then break when the user gets it right.

    drink_list = ['fanta', 'coke', 'pepsi', 'sprite']
    if choice in drink_list:
        break
    

提交回复
热议问题