-1

The following code should run smoothly, but for some reason Terminal tells me that there is a problem with it. My question is at the bottom.

print 'Welcome to Cash Calculator!'

cash = input('How much was the original price of the services or goods you paid for, excluding vat?')
tip = input('How much more, as a percentage, would you like to give as a tip?')

tip = tip/100

print tip

vat = 1.2

cash_vat = cash * vat

can = (cash_vat + ((tip/100) * cash_vat))

can = cash_vat + tip * cash_vat

print """
Thank you for your co-operation.
The price excluding the tip is %r,
and the total price is %d.
"""  % (cash_vat, can)

When the code above runs Terminal gives out:

Welcome to Cash Calculator!
How much was the original price of the services or goods you paid for, excluding vat?100
How much more, as a percentage, would you like to give as a tip?10
0

Thank you for your co-operation.
The price excluding the tip is 120.0,
and the total price is 120.

What seems to be the problem? It keeps thinking that the tip is 0. I am a complete beginner.

Morgan Thrapp
  • 8,618
  • 2
  • 43
  • 59

1 Answers1

2

In Python 2 the division operator / performes integer division if both the numerator and denominator are ints (which in this case they are, since you used input()). So the operation:

# if tip = 10
tip = 10/100

Will return 0, because both values are of type int.


Since you need float division, you can either import the division operator from the __future__ module:

from __future__ import division

tip = 10 / 100 # returns 0.1

Or, alternatively, cast the tip of type int to a float before actually dividing:

tip = float(10) / 100 # returns 0.1
Community
  • 1
  • 1
Dimitris Fasarakis Hilliard
  • 119,766
  • 27
  • 228
  • 224
  • @RichardDickins: if this answered your question, would you accept it? To do so, click the tick mark to the left of the answer - this is how we mark questions as solved and answers as correct. It is also a good way of recognising the effort of the poster, as it gives them a few extra reputation points. – halfer Jan 15 '16 at 08:15