python - for 循环中的 return 语句

标签 python loops

<分区>

我一直在为学校做这个作业,但我只是想不通为什么我不能让这个程序正常工作。我正在尝试让程序允许用户输入三种动物。它只允许我输入一个。我知道这与我在 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()

最佳答案

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

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

在这里,该函数会迭代,直到找到大海捞针的位置,然后返回该索引(尽管有一个内置函数可以执行此操作,无论如何,list.index())。

如果您希望该函数运行您指定的次数,则必须将返回放在 for 循环之后,而不是在循环内部。这样,该函数将在控件退出循环后返回

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

(不过,还有一个内置函数也可以执行此操作,sum())

关于python - for 循环中的 return 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5864166/

相关文章:

mysql - 在 MySQL 中循环结果集

python - 不同模型的训练精度不同,但测试精度相同

database - 如何在 VBA 中刷新循环或更新循环

python - 将 Python 列表值映射到字典值

javascript - 将 JavaScript 库移植到 Python

c++ - STL通过 map C++反向循环

java - 在java中,无效输入继续后重新提示用户的循环

java - 为什么我的整数增加了 2 而不是 1?

python - 在列表之间插入的最有效方法?

python - django local_settings导入错误