Python for循环 - 添加功能

时间:2016-02-07 01:34:50

标签: python-3.x

  1. 创建一个名为“cat_home”的列表。用五只猫填充列表。
  2. 循环浏览列表。在每次迭代中,让每只猫喵喵叫,战斗和吃。
  3. 所以我创建了第1步

    cat_home = ["Cat1", "Cat2", "Cat3", "Cat4", "Cat5"]
    

    然后我创建了循环:

    for x in cat_home:
        print(x)
    

    但我不知道如何进入第2步

    功能

    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 only 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")`
    

1 个答案:

答案 0 :(得分:0)

这是如何工作的每个函数都包含一个参数catpos或家中的位置。然后for循环循环,每次向x添加一个并更改cat的位置以及选择哪个cat。其他功能中使用sublifeaddlife

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 +" now only has",lives[catpos],"lives.")

def addlife(catpos):
    newlife = int(lives[catpos]) + 1
    lives[catpos] = newlife
    print(cat +" now has",lives[catpos],"lives.")

def meow(catpos):
    print(cat+" says meow.")

def fight(catpos):
    print("Scratch, arrgg, wrahh " + cat +" is fighting.")
    sublife(catpos)

def eat(catpos):
    print("Munch munch, yum yum! "+cat+" is eating.")
    addlife(catpos)

for x in range(len(cat_home)):
    fight(x - 1)
    eat(x - 1)
    meow(x - 1)