如何让用户在python 3.6.4中输入十进制数?

如何让用户在python 3.6.4中输入十进制数?,python,decimal,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

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

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))
price=input(“蔬菜的价格是多少?”)
磅=输入(“你买了多少磅?”)
价格=整数(价格)
磅=整数(磅)
如果磅数小于5:
价格=价格*1
打印(“您的价格为”+str(价格))
elif磅<10:
价格=价格*0.90
打印(“您的价格为”+str(价格))
elif磅<20:
价格=价格*0.80
打印(“您的价格为”+str(价格))
elif磅数>30:
价格=价格*0.75
打印(“您的价格为”+str(价格))
下面是错误:

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'
蔬菜的价格是多少?6.72
你买了多少英镑
回溯(最近一次呼叫最后一次):
文件“C:/Users/Jerry Cui/Documents/pricediscount.py”,第4行,在
价格=整数(价格)
ValueError:基数为10的int()的文本无效:“6.72”
有人能告诉我问题出在哪里吗?

使用
float()
,因为您想允许输入浮动

然而,我建议你,希望这能说服你按照以下思路纠正一些事情:

price = input("What is the price of your vegetable? (pounds.pence, e.g: 3.42)")
price = int(price.replace(".", ""))
现在,价格被存储为整数,这比浮点数精确得多;尤其是在存储货币时(因此我们在这里再次使用
int()

使用而不是:

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

  • 转换为整数
  • 转换为十进制数

int
表示整数。