This code is basically just a function that uses a value entered by the user. However, when the code multiplies 'population' and 'percent', the user receives the error in the title. What does this error mean? How can the code be modified in order to stop returning this error?
Here is my code:
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)
Here is the traceback:
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'
You have the order of self
and population
mixed up:
def populationCount(population, self):
That should be:
def populationCount(self, population):
Python will bind the arguments in the same order still, so in your method population
is the populationClass()
instance, and self
is bound to the value of population
passed in when you called the method.
In your definition of the function populationCount, please change the signature like below:
def populationCount(self, population):
Python is taking the passed parameter in the call as an instance of self, ie populationClass hence the error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.