John
John

Reputation: 3

How to add an unspecified amount of variables together?

I'm trying to add in python 3.5.2 but I have an unspecified amount of variables. I have to use very basic functions; I can't use list. I can't figure out how I'm supposed to add each new variable together without a list. When I run the code it adds the last entered price1 which is -1. I need to use the -1 to tell the program to total all the variables.

count = 0

while (True):

     price1 = int( input("Enter the price of item, or enter -1 to get total: "))

     count += 1

     if (price1 ==-1):
         subtotal = (price1 + ) #this is where I"m having trouble
                                #at least I think this is the problem
         tax = (subtotal*0.05)
         total = (subtotal + tax)

         print("Subtotal: .  .  . . . ", subtotal)
         print("Tax: . .  . . . . . . ", tax)
         print("Total: . . . . . . . .", total)

         break

Upvotes: 0

Views: 198

Answers (2)

idjaw
idjaw

Reputation: 26600

You almost had it. Looking at your code, what I would suggest you do is create a subtotal variable just outside of your loop and initialize it to 0. Furthermore, you are not using count for anything, so get rid of that.

When you get your price input, check it right after for the -1 condition. If you have a -1 value, then proceed with your math, otherwise your else will start running the subtotal with the subtotal += price.

So, you should have something like:

subtotal = 0
while (True):

     price = int( input("Enter the price of item, or enter -1 to get total: "))

     if price == -1:
         tax = subtotal*0.05
         total = subtotal + tax

         print("Subtotal: .  .  . . . ", subtotal)
         print("Tax: . .  . . . . . . ", tax)
         print("Total: . . . . . . . .", total)

         break
     else:
         subtotal += price

Upvotes: 1

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160657

Keep another variable around and sum than up, also, count isn't used for anything so no real reason to keep it around.

For example, initialize a price name to 0:

price = 0

then, check if the value is -1 and, if not, simply increment (+=) the price variable with the value obtained for price1:

if price1 == -1:
    subtotal = price 
    tax =  subtotal*0.05
    total = subtotal + tax

    print("Subtotal: .  .  . . . ", subtotal)
    print("Tax: . .  . . . . . . ", tax)
    print("Total: . . . . . . . .", total)

    break
else:
    price += price1

Upvotes: 2

Related Questions