for循环中的return语句

时间:2011-05-03 01:28:27

标签: python

我一直在为学校做这项任务,我无法弄清楚为什么我不能让这个程序正常工作。我正在尝试让程序允许用户输入三只动物。它只允许我输入一个。我知道它与我在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()

6 个答案:

答案 0 :(得分:26)

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

您的问题恰恰在于您将return语句放在for循环中。 for循环运行它中的每个语句但是很多次..如果你的一个语句是一个返回,那么该函数将在它命中时返回。例如,这在以下情况中是有意义的:

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

这里,函数迭代直到找到针在大海捞针中的位置,然后返回该索引(无论如何都有内置函数来执行此操作)。如果你希望函数运行很多次,你必须把它返回到for循环,而不是在它里面,这样,函数将在控件离开循环后返回

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

    return ret

(再一次,还有一个内置函数来执行此操作)

答案 1 :(得分:7)

你只需要在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

答案 2 :(得分:3)

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

答案 3 :(得分:2)

在返回前删除一个缩进。

答案 4 :(得分: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语句相同的深度),它会多次运行并给出正确的输出。

答案 5 :(得分:0)

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

相关问题