个人密码项目有时仅适用

时间:2018-08-29 03:49:41

标签: python

我写这段代码是因为我刚刚起步,想练习一下。这段代码在我尝试运行的每10次中只有1次有效。我用Jupyter Notebook写的。

当它不起作用时,我得到StateOverview,有时它说NameError: name 'oatcalories' is not defined.'也没有定义。

我如何确保它100%地有效?

这里是:

'eggcalories

这位新手感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您无需在最底端的break_total行中定义任何变量。如果您的代码是这样的,它应该可以正常工作:

eggcalories = 0
oatcalories = 0
avcalories = 0
toastcalories = 0
butcalories = 0

while True:

    one = input("What are you eating for breakfast? (Enter one item at a time and 'done' when done)\n")

    if one == "done":

        print ("Done")

        break

    if one.lower() == "eggs":
        quantegg = input("How many eggs? ")
        eggcalories = (int(quantegg) * 78)
    elif one.lower() == "oatmeal":
        quantoat = input("How many servings of oatmeal? ")
        oatcalories = (int(quantoat) * 120)
    elif one.lower() == "avacado":
        quantav = input("How many avacados: ")
        avcalories = (int(quantav) * 120)
    elif one.lower() == "toast":
        quantoast = input("How many pieces of toast?: ")
        toastcalories = (int(quantoast) * 70)
        butter = input("Did you add butter?")
        if butter.lower()[0] == "y":
            quantbut = input("How many servings of butter?: ")
            butcalories = (int(quantbut) * 102)
        elif butter.lower()[0] == "n":
            butcalories = (int(quantbut) * 0)
    else:
        pass

break_total =  eggcalories + oatcalories + avcalories + toastcalories + butcalories
print ("Total calories for breakfast:",break_total)

错误原因是因为您试图添加尚未设置的内容,因此当您尝试添加它们时,解释器不知道您要引用的内容。