如何在python 3中删除过多的if / elif语句

时间:2017-06-15 11:05:39

标签: python-3.x

我刚刚开始编程,并且学习了python 3.这是我写的第一个大程序,它可以工作,但是我有太多的if / elif语句。一位在谷歌担任软件工程师的朋友建议我发挥作用,我已经尝试过研究它,但却找不到明确的答案。我的问题如下:

** 1。如何整合所有if / elif语句以使其更具可读性?

  1. 我想为这些项目添加费用并自动加起来,我该怎么做呢?

  2. 如果用户输入"否"或"不"在问题中,如果我们的订单正确,我该如何返回菜单屏幕?只有食品和成本?并且循环(对不起,如果术语不正确)重复该过程?**

  3. 感谢所有帮助过的人!我在下面提供了我的代码:

    print("\nWelcome to Paul's Corner! We have a variety of foods available. 
    Please choose from these options:")
    print("\n................")
    print("\n1. Pizza - $9.00")
    print("2. Pasta - $12.00")
    print("3. House Salad - $8.00")
    print("4. Soup - $4.00\n")
    
    food = input("> ")
    
    if food == "Pizza" or food == "pizza":
        print("\nYou have chosen Pizza! Excellent choice! Now, What would you like to drink?")
        print("\n1. Sprite - $1.00")
        print("2. Orange Fanta - $1.00")
        print("3. Coke - $1.00")
        print("4. Diet Coke - $1.00")
    
    
    drink1 = input("> ")
    
    if drink1 == "Sprite" or drink1 == "sprite":
        print("Great! So, your order is a Pizza and a Sprite, is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer1 = input("> ")
    
    
        if answer1 == "Yes" or answer1 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer1 == "No" or answer1 == "no":
            print("We're sorry. What would you like instead?")
    
    
    elif drink1 == "Orange Fanta" or drink1 == "orange fanta" or drink1 ==  "Fanta" or drink1 == "fanta":
        print("Great! So, your order is Pizza and Fanta. Is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer2 = input()
    
        if answer2 == "Yes" or answer2 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer2 == "No" or answer2 == "no":
            print("We're sorry. WHat would you like instead?")
    
    elif drink1 == "Coke" or drink1 == "coke":
        print("Great! So, your order is Pizza and Coke. Is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer3 = input()
    
        if answer3 == "Yes" or answer3 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer3 == "No" or answer3 == "no":
            print("We're sorry. WHat would you like instead?")
    
    elif drink1 == "Diet Coke" or drink1 == "diet coke":
        print("Great! So, your order is Pizza and Diet Coke. Is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer4 = input()
    
        if answer4 == "Yes" or answer4 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer4 == "No" or answer4 == "no":
            print("We're sorry. WHat would you like instead?")
    
    
    
    
    #---------------------------------------------------------------------------------------
    
    
    
    
    elif food == "2" or food == "Pasta" or food == "pasta":
        print("\n You have chosen Pasta! Excellent choice! Now, what would you like to drink?")
        print("\n1. Sprite")
        print("2. Orange Fanta")
        print("3. Coke")
        print("4. Diet Coke\n")
    
    drink2 = input("> ")
    
    if drink2 == "Sprite" or drink2 == "sprite":
        print("Great! So, your orer is a Pizza and a Sprite, is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer5 = input("> ")
    
        if answer5 == "Yes" or answer5 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer5 == "No" or answer5 == "no":
            print("We're sorry. What would you like instead?")
    
    elif drink2 == "Orange Fanta" or drink2 == "orange fanta" or drink2 == "Fanta" or drink2 == "fanta":
        print("Great! So, your order is Pizza and Fanta. Is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer6 = input()
    
        if answer6 == "Yes" or answer6== "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer6 == "No" or answer6 == "no":
            print("We're sorry. WHat would you like instead?")
    
    elif drink2 == "Coke" or drink2 == "coke":
        print("Great! So, your order is Pizza and Coke. Is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer7 = input()
    
        if answer7 == "Yes" or answer7 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer7 == "No" or answer7 == "no":
            print("We're sorry. WHat would you like instead?")
    
    elif drink2 == "Diet Coke" or drink2 == "diet coke" :
        print("Great! So, your order is Pizza and Diet Coke. Is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer8 = input()
    
        if answer8 == "Yes" or answer8 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer8 == "No" or answer8 == "no":
            print("We're sorry. WHat would you like instead?")
    
    
    
    #----------------------------------------------------------------------------------------
    
    
    
    elif food == "House Salad" or food == "house salad" or food == "Salad" or food == "salad":
    print("\n You have chosen our House Salad! Excellent choice! Now, what would you like to drink?")
    print("\n1. Sprite")
    print("2. Orange Fanta")
    print("3. Coke")
    print("4. Diet Coke\n")
    
    drink3 = input("> ")
    
    if drink3 == "Sprite" or drink3 == "sprite":
        print("Great! So, your orer is a Pizza and a Sprite, is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer9 = input("> ")
    
        if answer9 == "Yes" or answer9 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer9 == "No" or answer9 == "no":
            print("We're sorry. What would you like instead?")
    
    elif drink3 == "Orange Fanta" or drink3 == "orange fanta" or drink3 == "Fanta" or drink3 == "fanta":
        print("Great! So, your order is Pizza and Fanta. Is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer10 = input()
    
        if answer10 == "Yes" or answer10== "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer10 == "No" or answer10 == "no":
            print("We're sorry. WHat would you like instead?")
    
    elif drink3 == "Coke" or drink3 == "coke":
        print("Great! So, your order is Pizza and Coke. Is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer11 = input()
    
        if answer11 == "Yes" or answer11 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer11 == "No" or answer11 == "no":
            print("We're sorry. WHat would you like instead?")
    
    elif drink3 == "Diet Coke" or drink3 == "diet coke" :
        print("Great! So, your order is Pizza and Diet Coke. Is that correct\n?")
        print("1. Yes")
        print("2. No\n")
    
        answer12 = input()
    
        if answer12 == "Yes" or answer12 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer12 == "No" or answer12 == "no":
            print("We're sorry. WHat would you like instead?")
    
    
    
    
    #-----------------------------------------------------------------------------------------------------------------------------
    
    
    
    
    
    elif food == "Soup" or food == "soup":
    print("\n You have chosen our Soup! Excellent choice! Now, what would you like to drink?")
    print("\n1. Sprite")
    print("2. Orange Fanta")
    print("3. Coke")
    print("4. Diet Coke\n")
    
    drink4 = input("> ")
    
    if drink4 == "Sprite" or drink4 == "sprite":
        print("Great! So, your orer is a Pizza and a Sprite, is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer13 = input("> ")
    
        if answer13 == "Yes" or answer13 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer13 == "No" or answer13 == "no":
            print("We're sorry. What would you like instead?")
    
    elif drink4 == "Orange Fanta" or drink4 == "orange fanta" or drink4 == "Fanta" or drink4 == "fanta":
        print("Great! So, your order is Pizza and Fanta. Is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer14 = input()
    
        if answer14 == "Yes" or answer14 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer14 == "No" or answer14 == "no":
            print("We're sorry. WHat would you like instead?")
    
    elif drink4 == "Coke" or drink4 == "coke":
        print("Great! So, your order is Pizza and Coke. Is that correct?")
        print("1. Yes")
        print("2. No")
    
        answer15 = input()
    
        if answer15 == "Yes" or answer15 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer15 == "No" or answer15 == "no":
            print("We're sorry. WHat would you like instead?")
    
    elif drink4 == "Diet Coke" or drink4 == "diet coke" :
        print("Great! So, your order is Pizza and Diet Coke. Is that correct\n?")
        print("1. Yes")
        print("2. No\n")
    
        answer16 = input()
    
        if answer16 == "Yes" or answer16 == "yes":
            print("Great! Thank you for choosing Paul's Corner!")
    
        elif answer16 == "No" or answer16 == "no":
            print("We're sorry. WHat would you like instead?")
    

3 个答案:

答案 0 :(得分:0)

您可以尝试以下方法。即将你可能的答案放在字典中。

def exec_sprite():
    print("Great! Sprite...")
    ## YOUR CODE HERE

def exec_coke():
    print("Great! Coke...")

def exec_orange_fanta():
    print("Great! Orange Fanta...")

drinks = {
        "sprite" : exec_sprite,
        "coke" : exec_coke,
        "orange fanta" : exec_orange_fanta}

try:
    drink1 = input("> ")
    drinks[drink1.lower()]()
    #break # with while(true) to break out of it
except KeyError as e:
    print("Sorry, did not understand.")
    print(e)

您甚至可以将try: ... except...封装在while(true)循环中,以确保用户可以再次选择。 现在,对于小的重复性事情,这可能是正确的。

如果它变得更加复杂,请查看类以使代码更清晰。 即class Drinks并将exec_*放在那里

答案 1 :(得分:0)

main_menu = """Welcome to Paul's Corner! We have a variety of foods available. 
Please choose from these options:)
................
1. Pizza - $9.00
2. Pasta - $12.00
3. House Salad - $8.00
4. Soup - $4.00"""

food_list = {1:'Pizza', 2:'Pasta', 3:'House Salad', 4:'Soup'}
#drinks_list = {1:'coke', ......

def get_food_type(list_of_options: dict, menu: str) -> "the selected food":
    print(menu)
    print("Please select number> ", end='')
    while True:
        choice = int(input())
        if choice in range(1, len(list_of_options)+1):
            selection =list_of_options[choice]
            if confirm_choice(choice):
                return choice
        else:
            print("Try again: ", end='')

def confirm_choice(choice):
    print("You have selected", choice, "is that correct? (y/n) ", end='')
    while True:
        choice = input().lower()
        if choice == 'y':
            return True
        if choice == 'n':
            return False
        print("Invalid selection, Try again", end='')

main_course_food = get_food_type(food_list, main_menu)
#get_food_type(drinks_list, drinks_menu)
#ect ect...

你可以得到比这更浓缩的内容,你现在要做的就是为每个项目制作一个字典,然后将其菜单输入到函数中。说真的,学习基础知识。获得一本有练习的书,并通过它练习。

答案 2 :(得分:0)

实际上,您可以通过使用包含所有食物和饮料的数据结构来避免重复,并对其进行迭代。这样你只需要一次逻辑。

以下是如何做到这一点:

foods = {
    "Pizza":  9.00,
    "Pasta": 12.00,
    "House Salad": 8.00,
    "Soup": 4.00
}

drinks = {
    "Sprite":  1.00,
    "Orange Fanta": 1.00,
    "Coke": 1.00,
    "Diet Coke": 1.00
}

def getChoice(choices):
    items = [(key, value) for key, value in choices.items()]
    text = "\n".join([
        "{}. {}".format(i+1, s) 
            for i, s in enumerate(["{}: - ${:.2f}".format(key, value) 
                for key, value in items])
    ])
    print(text + "\n")
    while True:
        choice = input("> ")
        if choice.title() in choices:
            break
        try:
            choiceNum = int(choice) - 1
            if choiceNum >= 0:
                choice = items[choiceNum][0]
                #choice = choiceText
                break
        except (ValueError, IndexError):
            pass
        print("\nI did not understand '{}'. Please try again...".format(choice))

    choice = choice.title()
    print("\nYou have chosen {}! Excellent choice!\n".format(choice))
    return choice

print("\nWelcome to Paul's Corner! We have a variety of foods available. Please choose from these options:")
print("\n................\n")

while True:
    food = getChoice(foods)

    print("Now, What would you like to drink?")
    drink = getChoice(drinks)

    print("Great! So, your order is a {} and a {}, is that correct?".format(food, drink))
    print("1. Yes")
    print("2. No")

    confirmed = input("> ")

    if confirmed.lower() == "yes" or confirmed == '1':
        print("Great! Thank you for choosing Paul's Corner!")
        break
    print("We're sorry. What would you like instead?")

repl.it上看到它。