首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基本Python For-Loops

基本Python For-Loops
EN

Stack Overflow用户
提问于 2012-08-22 03:49:19
回答 9查看 349关注 0票数 0

我很抱歉问了这么愚蠢的问题。

我是通过视频和书籍学习Python的,真的没有其他帮助。

在基本的python编程上找不到简单的区别。

########################################AAAAAA

代码语言:javascript
复制
    costs = [5,10,15,20]

    def sum_cart(item):
        total_cost = 0
        for this in costs:
            this = this + total_cost
        return total_cost
    print sum_cart(costs)

########################################BBBBBB

代码语言:javascript
复制
    def sum_cart(item):
        total_cost = 0
        for this in costs:
            total_cost = this + total_cost
        return total_cost
    print sum_cart(costs)

#########################################CCCCCC

代码语言:javascript
复制
    def sum_cart(item):
        total_cost = 0
        for this in costs:
            total_cost = this + total_cost
            return total_cost
    print sum_cart(costs)

-问题

结果是A --> 0,B --> 50,C --> 5

我仍然不明白为什么结果会是这样的。

如果我的理解是正确的,在A中,'this‘从列表中得到5,并将5添加到total_cost,即0。然后'this‘分别调用10、15和20,'this’得到一个新值。但是,由于total_cost仍然为0,因此结果为0。我说的对吗?

然后在B中,当调用'this‘= 5并将其添加到当前的' total_cost’=0(即5)时,更新total_cost。循环返回并分别引入10、15和20,'total_cost‘被更新为50。到目前为止,我认为一切都很好。

但是在C中,我不确定发生了什么,因为当'this‘从列表中取值为5时,'total_cost’就会更新。那么它应该返回' total_cost‘为5。for循环不应该返回并执行total_cost = this (假设为10) +total_cost(当前为5),然后再次执行该循环吗?关于"return“函数,我遗漏了什么?

EN

回答 9

Stack Overflow用户

发布于 2012-08-22 03:53:10

你的前两个假设是正确的。

在C中,return会立即退出函数。此时循环中止,返回total_cost (此时为5 )。

票数 2
EN

Stack Overflow用户

发布于 2012-08-22 04:06:53

这三个人都有写错的地方。你应该写一些类似这样的东西:

代码语言:javascript
复制
costs = [5,10,15,20]

def sum_cart(items):
    total = 0
    for item in items:
        total = total + item
    return total

print sum_cart(costs)

即使是你的例子B,尽管它得到了正确的答案,因为你传入了参数item,但在你的循环中,你循环了全局变量costs (所以你实际上没有使用你传递给函数的参数)。

票数 1
EN

Stack Overflow用户

发布于 2012-08-22 03:53:00

return从整个函数返回并结束它。在第三个示例中,for循环只运行一次。在第一次运行结束时,函数返回,并且for循环的其余部分永远不会发生。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12062002

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档