0

I am trying to make a program related to money and the user needs to input a decimal. But it always gives me an error. Here is the code:

price = input("What is the price of your vegetable?")
pounds = input("How many pounds did you buy?")

price = int(price)
pounds = int(pounds)

if pounds < 5:
    price = price * 1
    print("Your price is " + str(price))
elif pounds < 10:
    price = price * 0.90
    print("Your price is " + str(price))
elif pounds < 20:
    price = price * 0.80
    print("Your price is " + str(price))
elif pounds > 30:
    price = price * 0.75
    print("Your price is " + str(price))

And here is the error:

What is the price of your vegetable?6.72
How many pounds did you buy?4
Traceback (most recent call last):
File "C:/Users/Jerry Cui/Documents/pricediscount.py", line 4, in <module>
    price = int(price)
ValueError: invalid literal for int() with base 10: '6.72'

Where is the problem?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Jerry Cui
  • 149
  • 7

3 Answers3

2

Use float() instead of int():

price = float(price)
pounds = float(pounds)

  • int() converts to an integer
  • float() converts to a decimal
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
1

Use float() as you want to allow entry of floats!

However, I suggest you read this, which hopefully will convince you to right something along the lines of:

price = input("What is the price of your vegetable? (pounds.pence, e.g: 3.42)")
price = int(price.replace(".", ""))

Now the price is stored as an integer, which is much more accurate than a float; especially when storing money (hence we use int() here again).

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
0

If your dealing with financial data it is best to employ the decimal module. The according to the docs see decimal — Decimal fixed point and floating point arithmetic the module provides support for fast correctly-rounded decimal floating point arithmetic. It offers several advantages over the float datatype. To use in your particular situation:

price = input("What is the price of your vegetable? (pounds.pence, e.g: 3.42)")
price = Decimal(price).quantize(Decimal('.01'), rounding=ROUND_DOWN))

As examples:
print(Decimal('12.345').quantize(Decimal('.01'), rounding=ROUND_DOWN))) -> 12.34 , and

print(Decimal(''123.0056'').quantize(Decimal('.01'), rounding=ROUND_DOWN))) -> 123.00

itprorh66
  • 3,110
  • 4
  • 9
  • 21