为什么我得到错误不能将序列乘以'float'PYTHON类型的非int

时间:2012-11-03 12:06:41

标签: python

我写了一个简单的程序来计算某些电气部件的税,它是这样的:

print "How much does it cost?",    
price = raw_input()    
print "Tax: %s" % (price * 0.25)    
print "Price including tax: %s" % (price * 1.25)    
raw_input ("Press ENTER to exit")

我一直收到这个错误:

Traceback (most recent call last):
  File "moms.py", line 3, in <module>
    print "Tax: %s" % (price * 0.25)
TypeError: can't multiply sequence by non-int of type 'float'

4 个答案:

答案 0 :(得分:2)

您需要先将raw_input()返回的字符串转换为float

price = float(raw_input("How much does it cost?")) # no need for extra print 

答案 1 :(得分:1)

这意味着price不是数字。实际上,它是一个字符串,因为这是raw_input返回的内容。您需要使用float解析它,或使用input代替raw_input

答案 2 :(得分:1)

基本上你不能用浮点数乘以一个字符串,也许你想要的是

price = float(raw_input())

答案 3 :(得分:1)

price是一个字符串。您需要从输入的字符串中创建一个浮点数:

>>> price_str = raw_input()
123.234
>>> print type(price)
<type 'str'>
>>> price = float(price_str)
>>> print type(price)
<type 'float'>
>>> print "Tax: %s" % (price * 0.25)   
Tax: 30.8085
>>>