重叠变量不会改变变量

时间:2016-10-25 14:08:08

标签: python variables

我甚至无法解释。这是我的代码

foods = {12345670 : 'orange(s)',
     87654325 : 'pineapple(s)'}
loop = 10
while loop == 10:
    full_list = input("Type: ")
    if full_list == 'end':
        break
    amount = int(input("Amount: "))
    subtotal = 0
    item = int(full_list)
    if item in foods:
        print("That would be {} {}".format(amount, foods[item]))
        if full_list == '12345670':
            price = (0.50 * amount)
            print("Added Orange(s)")
            print("Added "+str(price))
            subtotal = subtotal + price
        if full_list == '87654325':
            price = (1.00 * amount)
            subtotal = subtotal + price
            print("Added Pineapple(s)")
            print("Added "+str(price))
print("Your subtotal is " +str(subtotal))

我正在尝试根据用户购买的内容来改变我的小计,我还没有完成我的可购买项目列表,所以我不想每次都更改变量的名称。这里有什么问题?为什么变量subtotal没有变化?

2 个答案:

答案 0 :(得分:1)

foods = {12345670 : 'orange(s)',
     87654325 : 'pineapple(s)'}
loop = 10
subtotal = 0             # <------ moved it outside of the while loop
while loop == 10:
    full_list = input("Type: ")
    if full_list == 'end':
        break
    amount = int(input("Amount: "))
    item = int(full_list)
    if item in foods:
        print("That would be {} {}".format(amount, foods[item]))
        if full_list == '12345670':
            price = (0.50 * amount)
            print("Added Orange(s)")
            print("Added "+str(price))
            subtotal = subtotal + price
        if full_list == '87654325':   #should be an elif not an if
            price = (1.00 * amount)
            subtotal = subtotal + price
            print("Added Pineapple(s)")
            print("Added "+str(price))
print("Your subtotal is " +str(subtotal))

每次循环时,您都会将总费用重新设置为0,并且只保留最新价格。将它移到我评论的while循环之外,你应该没问题。如果要将类似的elif语句链接在一起,也可以使用if

答案 1 :(得分:0)

您有以下

if full_list == '12345670'

但是它永远不会输入这个if语句,因为你的输入类型是一个整数而不是一个字符串。如果没有单引号,请执行此操作:

if full_list == 12345670