Python for loop - adding function -
- create list called ‘cat_home’. populate list 5 cats.
- loop through list. on each iteration make each cat meow, fight , eat.
so have created step 1 is
cat_home = ["cat1", "cat2", "cat3", "cat4", "cat5"] then have created loop:
for x in cat_home: print(x) but have no idea how proceed onto step 2
functions:
def meow (self): print(self.name, "says meow") def fight (self): print("scratch, arrgg, wrahh", self.name, "is fighting") self.lives -=1 print(self.name, "now has", self.lives,"lives") def eat (self): print("munch munch, yum yum!", self.name, "is eating") self.lives +=1 print(self.name, "now has", self.lives,"lives")`
how works each function takes in 1 parameter, catpos or position in home. for loop cycles through, adding 1 x each time , changing cat's position , cat selected. sublife , addlife used inside of other functions.
cat_home = ["cat1", "cat2", "cat3", "cat4", "cat5"] catpos = 0 lives = [9,9,9,9,9] cat = cat_home[catpos] def sublife(catpos): newlife = int(lives[catpos]) - 1 lives[catpos] = newlife print(cat +" has",lives[catpos],"lives.") def addlife(catpos): newlife = int(lives[catpos]) + 1 lives[catpos] = newlife print(cat +" has",lives[catpos],"lives.") def meow(catpos): print(cat+" says meow.") def fight(catpos): print("scratch, arrgg, wrahh " + cat +" fighting.") sublife(catpos) def eat(catpos): print("munch munch, yum yum! "+cat+" eating.") addlife(catpos) x in range(len(cat_home)): fight(x - 1) eat(x - 1) meow(x - 1)
Comments
Post a Comment