如何进行while循环,该循环继续循环,直到python中的totalamount等于0

问题描述 投票:-1回答:1

每份的份量应有限菜单上的菜式有15种达根人,2种蔬菜,5种清真食品。要求没有剩菜的菜应该返回消息“对不起,没有今天还有更多。”

我如何在循环中继续附加的代码,直到总数等于0。调试代码时收到此错误:发生异常:分配前已引用UnboundLocalError局部变量'data'

Example run:
What would you like today? (type 'how is business?' to attempt small talk, or 'not hungry' to stop)
> Vegetar
Vegetar, here you go.
What would you like today? (type 'how is business?' to attempt small talk, or 'not hungry' to stop)
> Vegetar
Vegetar, here you go.
What would you like today? (type 'how is business?' to attempt small talk, or 'not hungry' to stop)
> Vegetar
Sorry, no more left of <Vegetar> today.
What would you like today? (type 'how is business?' to attempt small talk, or 'not hungry' to stop)
> [...]


def salg():
    totalDagens = 15
    totalVegetar = 2
    totalHalal = 5

    while totalDagens <=0 and totalVegetar <=0 and totalHalal <=0:

        print("What would you like today?")
        data = input()

    if data == "Dagens":
        totalDagens = totalDagens - 1
        print("Dagens, her you go.")
    elif data == "Vegetar":
        totalVegetar = totalVegetar - 1
        print("Vegetar, here you go.")
    elif data == "Halal":
        totalHalal = totalHalal - 1
        print("Halal, here you go.")


salg()
python
1个回答
0
投票

我认为您的意思是>而不是<=。如果碟子的数字为0,则无法给出。可以在while循环中调用函数。这样的事情。如果您想在所有内容均为0时中断循环,则可以使用break

totalDagens = 15 #maintain the inventory globally
totalVegetar = 2
totalHalal = 5


def salg():
    data = input("What would you like today?")
    if data.lower() == "dagens": # just to make sure case insensitive
        totalDagens -= 1; print("Dagens, her you go.") if totalDagens > 0 else print("NoDangens left")
    elif data.lower() == "vegetar":
        totalVegetar -= 1; print("Vegetar, her you go.") if totalVegetar > 0 else print("No Vegetar left")
    elif data.lower() == "halal":
        totalHalal -= 1; print("Halal, her you go.") if totalHalal > 0 else print("No Halal left")

while True:
    salg()
    if totalDagens + totalVegetar + totalHalal == 0:
       break

print("Everything is sold")
© www.soinside.com 2019 - 2024. All rights reserved.