I am a noob to Python and have not had any luck figuring this out. I want to be able to keep the tax variable in the code so it would be easily updated should it change. I have experimented with different means but was only able to get it to skip the print tax line and print the same values for the total and subtotal. How do I multiply the tax variable by sum(items_count)? Here is the code:
items_count = []
tax = float(.06)
y = 0
count = raw_input('How many items do you have? ')
while count > 0:
price = float(raw_input('Please enter the price of your item: '))
items_count.append(price)
count = int(count) - 1
print 'The subtotal of your items is: ' '$%.2f' % sum(items_count)
print 'The amount of sales tax is: ' '$%.2f' % sum(items_count) * tax
total = (sum(items_count) * tax) + sum(items_count)
print 'The total of your items is: ' '$%.2f' % total
It would help if you provide the back-trace for the error. I ran your code, and got this back-trace:
The answer is that this is a precedence problem. If you just did this:
it would work, but because you have the expression with the string and the
%operator, the call tosum()is tied to the string, and effectively you have:The solution is to add parentheses to force the precedence you want:
Here is documentation of operator precedence in Python.
http://docs.python.org/reference/expressions.html#summary
Note that
%has the same precedence as*, so the order is then controlled by the left-to-right rule. Thus, the string and the call tosum()are connected with the%operator, and you are left with<string_value> * tax.Note that instead of parentheses, you could also use an explicit temporary:
When you aren’t sure what is going on, sometimes it’s a good idea to start using explicit temporary variables, and check to see that each one is set to the value you were expecting.
P.S. You don’t actually need all the calls to
float(). The value0.06is already a float value, so it is sufficient to just say:I like to put the initial zero on fractions, but you can use either of
tax = 0.06ortax = .06, it doesn’t matter.I like how you convert the prices to float by wrapping the
raw_input()call infloat(). I suggest that you should do the same thing forcount, wrap theraw_input()call inint()to get anintvalue. Then the later expression can simply beIt’s a bit tricky that
countis initially set to a string and then re-bound later. If a silly or crazy user enters an invalid count,int()will raise an exception; it is better if the exception happens right away, right on the call toraw_input(), rather than later in a seemingly simple expression.And of course you aren’t using
yfor anything in your code sample.