我是编程新手,正在学习Python。我试图构建一个简单的程序,并在我的代码的第9行上收到TypeError。
我希望“ potearned”和“ curpart”都是浮点数,以便可以进行划分。为什么不能将这两个变量相除?
我尝试将代码中一些变量的数据类型更改为无效。最近,我尝试使用float()函数将操作数转换为浮点数,但这没有用。
我正在编写的代码是:
`begpart = input("How many participants started the game?")
curpart = input("How many participants are there left?")
bet = raw_input("How much did you bet?")
cutper = input(" What is stepbet's cut? (as decimal)")
float(cutper)
potearned = (begpart - curpart) * bet
float(curpart)
float(potearned)
earnper = potearned / curpart <------------ error line, line 9
cut = earnper
cut = earnper * cutper
float(cut)
pot = begpart * bet
float(pot)
print cut
print earnper
netearn = earnper - cut
print netearn
netearns = str(netearn)'
print "If noone else drops out you will earn " + netearns
我的预期结果是使整个程序运行而不会遇到typeerror。执行程序时发生的是我收到错误:
"Traceback (most recent call last):
File "python", line 9, in <module>
TypeError: unsupported operand type(s) for /: 'unicode' and 'int' "
答案 0 :(得分:0)
float(cutpart)
和其他类似的行不会将现有的cutpart
转换为浮点数;他们返回cutpart
的新版本,是浮点数。您虽然没有将返回的浮点保存到变量中,但却将其抛出。将该行(和其他类似的行)更改为:
cutpart = float(cutpart)
或者,适当的话,给它起一个新名字,以便在需要时仍可以引用pot
的先前版本:
float_cutpart = float(cutpart)
float_potearned = float(potearned)
earnper = float_cutpart / float_potearned