for循环中的return语句
我在做学校的作业,但我就是搞不懂为什么这个程序不能正常工作。我想让程序允许用户输入三种动物,但它只让我输入一种。我知道这跟我在make_list
函数里放置的返回语句有关,但我不知道该怎么修复它。
这是我的代码:
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 个回答
2
你的返回语句缩进的位置不对。它应该和for语句在同一个层级。把返回语句放在循环里面会导致它在循环中直接退出。
9
你只需要把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
31
你的问题正是因为你把返回语句放在了循环里面。循环会根据你设定的次数执行里面的每一条语句。如果其中有一条是返回语句,那么一旦执行到这条语句,函数就会立刻返回结果。这在下面这个例子中是可以理解的:
def get_index(needle, haystack):
for x in range(len(haystack)):
if haystack[x] == needle:
return x
在这里,函数会一直查找,直到找到“针”在“干草堆”中的位置,然后返回这个位置的索引(不过其实有一个内置函数可以做到这一点,就是 list.index()
)。
如果你希望函数按照你设定的次数运行,就必须把返回语句放在循环的后面,而不是里面。这样,函数会在循环结束后再返回结果。
def add(numbers):
ret = 0
for x in numbers:
ret = ret + x
return ret
(不过同样,也有一个内置函数可以做到这一点,就是 sum()
)