您遇到了类型转换问题。投射到 a float
(或 a int
,这里有一点关于两者之间的区别),一切都会好起来的。
a = float(input ("what is a"))
b = float(input ("what is b"))
您还应该考虑使用 Python 解释器。这是我尝试手动单步执行代码时得到的结果:
>>> a = input('what is a')
what is a3
>>> a*a # I put 3 in as my number, but it gave me the str value of '3'!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
我还建议try...except
帮助您提供更好的错误消息。如果你使用while
它,它也会成功,这样你就可以确保你有一些东西可以使用,例如:
# Make them keep inputting "a" until they give you something
# you can actually work with!
while 1:
try:
a = float(input ("what is a"))
break
except TypeError:
print('That was not a number! please try again')
注意:这在 Python 2.x 中不会发生,因为输入可以返回一个 int。