for 循环中的 return 语句[重复]
- 2025-02-08 08:52:00
- admin 原创
- 46
问题描述:
我一直在为学校做这项作业,但就是搞不清楚为什么我不能让这个程序正常工作。我试图让程序允许用户输入三种动物。它只允许我输入一种。我知道这与我在函数中放置返回语句有关,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()
解决方案 1:
您的问题恰恰在于您将 return 语句放在了 for 循环中。for 循环会运行其中的每个语句多次。如果您的某个语句是 return,那么函数在遇到该语句时就会返回。例如,在以下情况下,这是有道理的:
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()
)
解决方案 2:
您只需要返回pet_list
for 循环的外部,因此它会在循环运行结束后发生。
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
解决方案 3:
您的 return 语句的缩进级别不正确。它应该与 for 语句的缩进级别相同。在循环内使用 return 会导致循环跳出。
解决方案 4:
删除回车前的一个缩进。
解决方案 5:
您会注意到 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 语句相同的深度),它就会运行多次并给出正确的输出。
解决方案 6:
你的间距不对。返回 pet_list 在 for 循环的范围内。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD