[英]Why do I get error can't multiply sequence by non-int of type 'float' PYTHON
I wrote a simple program to calculate tax for some electrical parts, it goes like this: 我写了一个简单的程序来计算某些电气部件的税,它是这样的:
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")
And I keep getting this error: 我一直收到这个错误:
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'
您需要先将raw_input()
返回的字符串转换为float
:
price = float(raw_input("How much does it cost?")) # no need for extra print
This means that price
is not a number. 这意味着price
不是数字。 In fact, it's a string, since that's what raw_input
returns. 实际上,它是一个字符串,因为这是raw_input
返回的内容。 You'll want to parse it using float
, or use input
instead of raw_input
. 您将要使用float
解析它,或使用input
而不是raw_input
。
基本上你不能将一个字符串乘以浮点数,也许你想要的是
price = float(raw_input())
The price
is a string. price
是一个字符串。 You need to create a float from the string you have input: 您需要从输入的字符串创建一个浮点数:
>>> 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
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.