wro*_*ame 3 python string floating-point python-3.x
我收到
TypeError: Can't convert 'float' object to str implicitly
Run Code Online (Sandbox Code Playgroud)
使用时
Gambler.pot += round(self.bet + self.money * 0.1)
Run Code Online (Sandbox Code Playgroud)
锅,赌注和金钱都是双打(或至少应该是).我不确定这是否是另一个Eclipse的东西,但我如何让这行编译?
代码在何处bet和money初始化:
class Gambler:
money = 0
bet = 0
Run Code Online (Sandbox Code Playgroud)
测试用例:
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)))
Run Code Online (Sandbox Code Playgroud)
测试用例的输出:
Here, the number is a <class 'int'>
Enter in something: 1
But now, it has turned into a <class 'str'>
Run Code Online (Sandbox Code Playgroud)
显然,input()正在将其更改为字符串.
编辑:最后解决了问题(我认为)
self.bet = int(self.bet.strip())
Run Code Online (Sandbox Code Playgroud)
在用户输入值之后.虽然我不知道如果这是解决问题的最佳方法:)
Daniel G的更好解决方案:
self.bet = float(input("How much would you like to bet? $"))
Run Code Online (Sandbox Code Playgroud)
input()在3.x中只返回字符串.程序员的工作是将它传递给数字构造函数,以便将其转换为数字.