我正在尝试用Python制作一个英寸到厘米(反之亦然)转换器。
print "CM TO INCH (VV) CONVERSION. ENTER SPECIFIED NUMBER:"
inches = 2.54 #centimetres
cms = 0.393701 #inches
number = raw_input()
answercms = number * inches
answerinches = number * cms
print "%d centimetres are %d inches. %d inches are %d centimetres." % (number, answerCms, number, answerinches)
在Powershell中运行脚本后,会出现此错误:
Traceback (most recent call last):
File "inchcm.py", line 5, in <module>
answercms = number * inches
TypeError: can't multiply sequence by non-int of type 'float'
我知道这个问题已经出现过一两次,但我不明白答案。
答案 0 :(得分:2)
raw_input()
返回一个字符串。您不能将字符串与数字相乘,因此您需要首先将数字字符串转换为实际数字格式,例如使用float()
函数:
number = raw_input()
answercms = float(number) * inches
您可以使用type()
来检查变量的实际类型:
>>> type(number)
<type 'str'>
>>> type(float(number))
<type 'float'>