for循环中的return语句

Bra*_*ite 7 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()
Run Code Online (Sandbox Code Playgroud)

Lac*_*ogy 26

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

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

def get_index(needle, haystack):
    for x in range(len(haystack)):
        if haystack[x] == needle:
            return x
Run Code Online (Sandbox Code Playgroud)

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

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

    return ret
Run Code Online (Sandbox Code Playgroud)

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


Aco*_*orn 8

您只需要返回pet_listfor循环的外部,因此它将在循环运行完毕后发生.

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
Run Code Online (Sandbox Code Playgroud)


Dan*_*ani 1

删除回车前的一个缩进。

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