【问题标题】:return statement in for loopsfor循环中的return语句
【发布时间】:2011-08-17 09:00:54
【问题描述】:

我一直在为学校完成这项任务,但我无法弄清楚为什么我无法让该程序正常运行。我正在尝试让程序允许用户输入三种动物。它只允许我输入一个。我知道这与我在 make_list 函数中放置 return 语句有关,但不知道如何修复它。

这是我的代码:

import pet_class

#The make_list function gets data from the user for three pets. The function
# returns a list of pet objects containing the data.
def make_list():
    #create empty list.
    pet_list = []

    #Add three pet objects to the list.
    print 'Enter data for three pets.'
    for count in range (1, 4):
        #get the pet data.
        print 'Pet number ' + str(count) + ':'
        name = raw_input('Enter the pet name:')
        animal = raw_input('Enter the pet animal type:')
        age = raw_input('Enter the pet age:')

        #create a new pet object in memory and assign it
        #to the pet variable
        pet = pet_class.PetName(name,animal,age)

        #Add the object to the list.
        pet_list.append(pet)

        #Return the list
        return pet_list

pets = make_list()

【问题讨论】:

标签: python loops


【解决方案1】:

你注意到 for 循环只运行一次,因为 return 语句在 if 语句内,在循环内

我的代码现在也遇到了类似的问题:

返回给定数组中偶数整数。注意: % "mod" 运算符计算余数,例如5 % 2 是 1。

count_evens([2, 1, 2, 3, 4]) → 3
count_evens([2, 2, 0]) → 3
count_evens([1, 3, 5]) → 0

def count_evens(nums):
    summary = 0
    for i in nums:

        if i % 2 == 0:
            summary += 1
            return summary    



count_evens([2, 1, 2, 3, 4]) 

如果你去可视化执行并粘贴我的代码http://www.pythontutor.com/visualize.html#mode=edit

一旦我将它取消缩进 8 个空格(与 for 语句的深度相同),它就会运行多次并给出正确的输出。

【讨论】:

    【解决方案2】:

    我只是再次回答这个问题,因为我注意到您的主题已经说明了问题,并且没有人给出..理论上的解释,这里..在这种情况下,理论这个词太大了,但无论如何。

    确切地说,您的问题是您将 return 语句放在 for 循环中。 for 循环运行其中的每个语句很多次.. 如果您的语句之一是返回,那么该函数将在遇到它时返回。这在例如以下情况下是有意义的:

    def get_index(needle, haystack):
        for x in range(len(haystack)):
            if haystack[x] == needle:
                return x
    

    这里,函数迭代直到找到大海捞针的位置,然后返回该索引(无论如何,有一个内置函数可以做到这一点)。如果您希望函数运行多次,则必须将 return 放在 for 循环之后,而不是放在里面,这样,函数将在控件退出循环后返回

    def add(numbers):
        ret = 0
        for x in numbers:
            ret = ret + x
    
        return ret
    

    (再一次,还有一个内置函数可以做到这一点)

    【讨论】:

      【解决方案3】:

      您的间距已关闭。 return pet_list 在 for 循环的范围内。

      【讨论】:

        【解决方案4】:

        您的 return 语句的缩进级别不正确。它应该与 for 语句处于相同的深度。在循环中返回会导致它跳出循环。

        【讨论】:

          【解决方案5】:

          您只需要在 for 循环之外返回 pet_list,这样它就会在循环运行完成后发生。

          def make_list():
              pet_list = []
          
              print 'Enter data for three pets.'
              for count in range (1, 4):
                  print 'Pet number ' + str(count) + ':'
                  name = raw_input('Enter the pet name:')
                  animal=raw_input('Enter the pet animal type:')
                  age=raw_input('Enter the pet age:')
                  print
          
                  pet = pet_class.PetName(name,animal,age)
                  pet_list.append(pet)
          
              return pet_list
          

          【讨论】:

          • 非常感谢。令人惊讶的是,如此简单的事情怎么会被忽视
          【解决方案6】:

          return 前删除一个缩进。

          【讨论】:

          • 更多细节会有所帮助:make_list() 中的 for 循环执行一次然后返回。在 python 中缩进很重要。