python为什么我的变量没有改变并使用我的字典

2024-06-16 10:57:45 发布

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

所以我在做一个课堂作业,基本上我必须这样做,但是当我运行我的程序时,它不会从我的字典中提取数字来添加它们。当我把热饮放入输入项时,它不会将4.25添加到num1或任何其他项中

import time

coffee = {"hot brew": 4.25,
 "latte": 4.75,
 "mocha": 4.99,
 "cold brew": 3.95,
 "cappuccino": 4.89,
 "dount": 1.50}
num8 = 0
while num8 == 0:


    num7=0
    while num7 == 0:
        items = input("what items would you like to buy or leave blank to end your order")

        num1=0
        num2=0
        num3=0
        num4=0
        num5=0
        num6=0


        total=0

        if items == "hot brew":
            num1 = num1 + coffee["hot brew"]
        elif items == "latte":
            num2 = num2 + coffee["latte"]
        elif items == "mocha":
            num3 = num3 + coffee["mocha"]
        elif items == "cold brew":
            num4 = num4 + coffee["cold brew"]
        elif items == "cappuccino":
            num5 = num5 + coffee["cappuccino"]
        elif items == "dount":
            num6 = num6 + coffee["dount"]
        elif items == "":
            num7 = num7 + 1
        else:
            print("that item does not exit")
    total = num1 + num2 + num3 + num4 + num5 + num6
    total = total * 1.07
    print ("your order is " + str(total) + "$")
    time.sleep(5)
    leave = input("would you like to close the program yes or no")
    if leave == "yes":
        num8 = 1
       

Tags: itemstotalcoffeebrewelifhotmochalatte
2条回答

num1到num8的赋值是在循环中进行的,因此在循环运行完之后,它会被重新赋值为零。在循环之外定义这些变量,也许就在咖啡字典之后,它就可以正常工作了

num1-num6变量是循环中的initialized。因此,每次循环递增时,这些变量都得到reassigned to zero。您必须在num7 == 0循环之外定义它

相关问题 更多 >