else命令运行不正确?(Python 3初学者)

2024-06-16 11:52:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的第一个Python程序开发一个组合菜单。到目前为止,我已经让一切正常工作。如果用户的输入不等于接受的答案,我希望程序退出。我尝试了几种不同的方法来让它工作,但它仍然像我回答的“是”或“是”一样运行。有什么帮助吗?非常感谢

这是我的密码:

def p(): #Prints new line quiokly
    print()

def error(): #Restarts the main
    question = input("You have entered an invalid option. Would you like to try your order again? \n")
    if question in ("Yes","yes","yes"):
        main()
    else:
        exit

def main(): #Main block of code
    cost = 0 #total cost variable
    if cost == 0:
        print("What type of sandwhich would you like? Refer to the cost and type of sandwhich below.")
        p()
        print("Chicken Sandwhich = $5.25")
        p()
        print("Tofu Sandwhich = $5.75")
        p()
        print("Beef Sandwhich = $6.25") #initial questions
        x = input()
        if x == ("Beef") or x == ("beef"):
            cost += 6.25
            print("You have selected Beef. Your total is so far is $6.25.")
        elif x == ("Chicken") or x == ("chicken"):
            cost += 5.25
            print("You have selected Chicken. Your total is so far is $5.25.")
        elif x == ("Tofu") or x == ("tofu"):
            cost += 5.75
            print("You have selected Tofu. Your total is so far is $5.75.")
        if x not in ("beef" , "Beef" , "Tofu" , "tofu" , "chicken" , "Chicken"): #checks for valid resposne
            error()


        print("Would you like to add a drink to your meal?")
        p()
        yzz = input()
        if yzz == ("Yes") or ("yes"):
            p()
            print("Okay, would you like small, medium, or large? Refer to the prices below.")
            print(cost)
            p()
            print("Small - $1.00")
            p()
            print("Medium - $1.75")
            p()
            print("Large - $2.25")
            p()
            yzzz = input()
            if yzzz == ("Small") or yzzz == ("small"):
                cost += 1
                print("You have selected a small drink. Your total is so far is " + "$%.2f" %cost + ".")
            elif yzzz == ("Medium") or yzzz == ("medium"):
                cost += 1.75    
                print("You have selected a medium drink. Your total is so far is " + "$%.2f" %cost + ".")
            elif yzzz == ("Large") or yzzz == ("large"):
                cost += 2.25
                print("You have selected a large drink. Your total is so far is " + "$%.2f" %cost + ".")
            if yzzz not in ("small" , "Small" , "Medium" , "medium" , "large" , "Large"): #checks for valid response
                error()
    elif yzz not in ("yes","Yes"):
        exit




#Main code starts here!
main()

Tags: ortoyouyourifsoishave
1条回答
网友
1楼 · 发布于 2024-06-16 11:52:35

elif yzz not in ("yes","Yes"):的缩进错误,需要再次缩进

此外,表达式if yzz == ('Yes') or ('yes')的计算结果将始终为True,因为or希望任意一侧都有一个布尔值,并且('yes')的计算结果为True

而是写if yzz in ['Yes', 'yes']

相关问题 更多 >