Python 将浮点数误认为字符串
我收到了
TypeError: Can't convert 'float' object to str implicitly
在使用
Gambler.pot += round(self.bet + self.money * 0.1)
的时候,pot、bet 和 money 都应该是双精度浮点数(double)。我不确定这是不是又一个 Eclipse 的问题,但我该怎么让这一行代码能编译通过呢?
这里是 bet
和 money
初始化的代码:
class Gambler:
money = 0
bet = 0
测试案例:
number = 0
print("Here, the number is a {0}".format(type(number)))
number = input("Enter in something: ")
print("But now, it has turned into a {0}".format(type(number)))
测试案例的输出:
Here, the number is a <class 'int'>
Enter in something: 1
But now, it has turned into a <class 'str'>
显然,input() 把它改成了字符串。
编辑:我终于解决了这个问题(我想)用的是
self.bet = int(self.bet.strip())
在用户输入值之后。不过我不知道这是不是解决问题的最好方法 :)
Daniel G. 提出的更好解决方案:
self.bet = float(input("How much would you like to bet? $"))
6 个回答
4
你有没有初始化pot?你有没有尝试保存一些中间结果来找出问题出在哪里?最后,你知道
pdb吗?这个可能会对你很有帮助。
class Gambler:
pot = 0.0
def __init__(self, money=0.0)
self.pot = 0.0
self.bet = 0.0
self.money = money
def update_pot(self):
import pdb; pdb.set_trace()
to_pot = self.bet + self.money * 0.1
to_pot = round(to_pot)
Gambler.pot = Gambler.pot + to_pot
当执行到set_trace()这一行时,你会看到一个提示。到时候可以看看当前的值是什么。
(Pdb) h # help
(Pdb) n # go to next statement
(Pdb) l # list source code
...
(Pdb) to_pot
...
(Pdb) self.bet
...
(Pdb) self.money
...
(Pdb) Gambler.pot
...
(Pdb) c # continue
6
在Python 3.x中,input()
这个函数只会返回字符串,也就是说你输入的内容会被当作文本处理。要把这个字符串变成数字,就得由程序员自己去用数字构造函数来转换。
3
Python3.2 (py3k:77602) 会出现这些错误信息:
>>> "1.2" * 0.1 #1 Traceback (most recent call last): File "", line 1, in TypeError: can't multiply sequence by non-int of type 'float' >>> "3.4" + 1.2 * 0.1 #2 Traceback (most recent call last): File "", line 1, in TypeError: Can't convert 'float' object to str implicitly >>> n = "42" >>> n += round(3.4 + 1.2 * 0.1) #3 Traceback (most recent call last): File "", line 1, in TypeError: Can't convert 'int' object to str implicitly
我怀疑你的错误信息是因为你实际使用的某个值是字符串,而不是预期中的浮点数,这种情况和第2种情况很相似,正好符合你的异常。
记住,Python 3.x 的 input 和 Python 2.x 的 raw_input 是一样的,而 Python 2.x 的 input 已经不再使用了(它相当于使用 eval,你不想这样做)。因此,Python 3.x 中的 input 始终会返回一个字符串。你可以用 int 来转换:
n = int(input("Enter a number: "))
如果你想处理输入错误,那么要捕获 ValueError,这是 int 在出错时会抛出的错误:
try:
n = int(input("Enter a number: "))
except ValueError:
print("invalid input")
else:
print("squared:", n*n)