3

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

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

4 回答 4

2

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

price = float(raw_input("How much does it cost?")) # no need for extra print 
于 2012-11-03T12:09:20.680 回答
1

这意味着这price不是一个数字。事实上,它是一个字符串,因为这就是raw_input返回的内容。你会想要使用 解析它float,或者使用input而不是raw_input.

于 2012-11-03T12:09:06.243 回答
1

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

price = float(raw_input())
于 2012-11-03T12:09:17.077 回答
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
>>> 
于 2012-11-03T12:11:20.417 回答