你如何让用户在python 3.6.4中输入小数?

时间:2018-04-02 20:06:26

标签: python decimal

我正在尝试制作与钱相关的程序,用户需要输入小数。但它总是给我一个错误。这是代码:

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

这是错误:

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'

有人能告诉我问题在哪里吗?

3 个答案:

答案 0 :(得分:2)

使用float(),因为您希望允许输入浮点数!

然而,我建议您read this,这有望说服您按照以下方式行事:

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

现在价格存储为整数, 比浮点数更精确;特别是在存钱时(因此我们再次使用int())。

答案 1 :(得分:1)

使用float()代替int()

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

答案 2 :(得分:0)

如果您处理财务数据,最好使用十进制模块。根据文档参见 decimal — Decimal fixed point and floating point arithmetic 该模块提供对快速正确舍入的十进制浮点运算的支持。与 float 数据类型相比,它提供了几个优点。在您的特定情况下使用:

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

例如:
print(Decimal('12.345').quantize(Decimal('.01'), rounding=ROUND_DOWN))) -> 12.34 和

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