个人代码项目有时才起作用

2024-06-25 23:41:03 发布

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

我写这段代码是因为我刚开始,想练习一下。这段代码每运行10次只有1次有效。我在Jupyter笔记本上写的。你知道吗

当它不工作时,我得到NameError: name 'oatcalories' is not defined.有时它说'eggcalories也没有定义。你知道吗

我如何确保它100%的工作时间?你知道吗

在这里:

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)

这个新手很感激你的帮助!你知道吗


Tags: ofinputifloweronemanyhowint
1条回答
网友
1楼 · 发布于 2024-06-25 23:41:03

您没有定义最下面的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)

错误的原因是因为您试图添加尚未设置的内容,所以当您尝试添加这些内容时,解释器不知道您引用的内容。你知道吗

相关问题 更多 >