FlagShipKILLER FlagShipKILLER - 1 month ago 9
Python Question

overlapping variable doesn't change variable

I can't even explain. Here is my code

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))


I'm trying to get my subtotal to change accordingly to what the user purchases, I haven't finished making my list of purchasable items and so I don't want to change the name of the variable every time. What is the problem here? Why doesn't the variable
subtotal
change?

Answer
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))

Every time you looped you restarted the total cost to 0 and it only kept the latest price. Move it outside of the while loop where I commented and you should be fine. Also use elif if you want to chain similar if statements together.