Python 如何修复TypeError:*:';实例';和';浮动';在函数中
该代码基本上只是一个使用用户输入值的函数。但是,当代码乘以“人口”和“百分比”时,用户会收到标题中的错误。这个错误意味着什么?如何修改代码以停止返回此错误 这是我的密码:Python 如何修复TypeError:*:';实例';和';浮动';在函数中,python,function,typeerror,Python,Function,Typeerror,该代码基本上只是一个使用用户输入值的函数。但是,当代码乘以“人口”和“百分比”时,用户会收到标题中的错误。这个错误意味着什么?如何修改代码以停止返回此错误 这是我的密码: import random import math class populationClass: food = 0 population = 0 percent = 0 def populationCount(population, self): while True
import random
import math
class populationClass:
food = 0
population = 0
percent = 0
def populationCount(population, self):
while True:
try:
food = int(raw_input("Variety of Foood: "))
if food > 0: break
else:
print "Enter a Positive Integer!"
except ValueError:
print "Enter a Positive Integer!"
if food == 1:
percent = 5
elif food == 2:
percent = 5
elif food == 3:
percent = 7
elif food == 4:
percent = 7
elif food == 5:
percent = 9
elif food == 6:
percent = 9
elif food >= 7:
percent = 11
else:
print "Enter a Positive Number!"
rand1 = random.randint(1,6)
rand2 = random.randint(1,6)
print rand1
print rand2
if rand1 == 1:
percent -= rand2
elif rand1 == 2:
percent += rand2
elif rand1 == 3:
percent -= rand2
elif rand1 == 4:
percent += rand2
elif rand1 == 5:
percent -= rand2
elif rand1 == 6:
percent += rand2
else:
print "Something Went Wrong"
percent = float(percent*.01) + 1.00
print percent
population = population*percent
print "New Population: " + str(int(population))
obj1=populationClass()
while True:
while True:
try:
population = int(raw_input("Population: "))
if population > 0: break
else:
print "Enter a Positive Integer!"
except ValueError:
print "Enter a Positive Integer!"
obj1.populationCount(population)
以下是回溯:
Traceback (most recent call last):
File "C:\Users\Andrew\Documents\pyscripts\Board Game Syllabus.py", line 116, in <module>
obj1.populationCount(population)
File "C:\Users\Andrew\Documents\pyscripts\Board Game Syllabus.py", line 66, in populationCount
population = population*percent
TypeError: unsupported operand type(s) for *: 'instance' and 'float'
回溯(最近一次呼叫最后一次):
文件“C:\Users\Andrew\Documents\pyscripts\Board Game Celletus.py”,第116行,在
obj1.人口计数(人口)
文件“C:\Users\Andrew\Documents\pyscripts\Board Game Celletus.py”,第66行,在populationCount中
人口=人口*百分比
TypeError:不支持*:“instance”和“float”的操作数类型
你把self
和population
的顺序搞混了:
def populationCount(population, self):
这应该是:
def populationCount(self, population):
Python仍将以相同的顺序绑定参数,因此在方法中,
population
是populationClass()
实例,self
绑定到调用该方法时传入的population
值。在函数populationCount的定义中,请更改以下签名:
def populationCount(self, population):
Python将调用中传递的参数作为self的实例,即populationClass,因此出现错误。请包含错误的完整回溯,只需在您的帖子中添加此类详细信息即可。