为什么在 For 循环中放错 Return 语句会影响输入循环?

Patricia Arquette
发布: 2024-10-19 07:23:30
原创
655 人浏览过

Why Does Misplacing the Return Statement in For Loops Affect Input Looping?

For 循环中的 Return 语句错位

在您的作业中,您遇到了一个问题,即程序只允许输入一只宠物,尽管瞄准三个。这个问题源于 make_list 函数中 return 语句的定位。

在 for 循环中,return 语句在到达函数时立即终止函数的执行。在提供的代码中,return 语句放置在循环内,导致函数在第一次迭代后退出,无论所需的输入数量(在本例中为三个)。

要纠正此问题, return 语句应该放在 for 循环之外。这确保了循环在函数结束之前运行规定的迭代次数。

这是更正后的 make_list 函数:

<code class="python">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</code>
登录后复制

通过将 return 语句放在循环之外,函数现在在返回宠物对象列表之前完全执行。

以上是为什么在 For 循环中放错 Return 语句会影响输入循环?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!