for循环中的return语句

for循环中的return语句

本文介绍了for循环中的return语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为学校做这项作业,但我不明白为什么我不能让这个程序正常运行.我试图让程序允许用户输入三只动物.它只允许我输入一个.我知道这与我在 make_list 函数中放置 return 语句有关,但不知道如何修复它.

I have been working on this assignment for school and I just can't figure out what why I cant get this program to work properly. I am trying to get the program to allow the user to enter three animals. It is only allowing me to enter one. I know it has to do with my placement of the return statement in the make_list function but can't figure out how to fix it.

这是我的代码:

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()

推荐答案

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

I'm only answering this again, because I notice that your subject already states the problem, and nobody's given a.. theoretical explanation, here.. theoretical being too big a word in this case, but whatever.

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

Your problem is, precisely, that you're putting the return statement inside the for-loop. The for-loop runs each statement in it for however so many times.. if one of your statements is a return, then the function will return when it hits it. This makes sense in, for example, the following case:

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

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

Here, the function iterates until it finds where the needle is in the haystack, and then returns that index (there's a builtin function to do this, anyways). If you want the function to run for however many times you tell it to, you have to put the return AFTER the for-loop, not inside it, that way, the function will return after the control gets off the loop

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

    return ret

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

(once again, there's a builtin function to do this as well)

这篇关于for循环中的return语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 06:42