Python 使用 for() 循环在范围内添加数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12964460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:16:35  来源:igfitidea点击:

Adding Numbers in a Range with for() Loop

python

提问by kylie.a

I'm having trouble filling out a question on an online python tutorial. It seems really simple but for the life of me I can't figure it out. This is the problem "write a for loop that adds all the numbers 1 to 10 and returns the sum." And this is the code I have been trying:

我在在线 Python 教程中填写问题时遇到问题。这看起来很简单,但对于我的生活,我无法弄清楚。这就是问题“编写一个 for 循环,将所有数字 1 到 10 相加并返回总和。”这是我一直在尝试的代码:

def run():
    sum = 0
    for i in range(11):
        sum += i
        return sum

What am I doing wrong? Thanks for any help.

我究竟做错了什么?谢谢你的帮助。

采纳答案by Platinum Azure

You're returning within the loop, after one iteration. You need to dedent the returnstatement so that it falls outside the loop:

经过一次迭代,您将在循环内返回。您需要删除该return语句,使其落在循环之外:

def run():
    sum_ = 0
    for i in range(11):
        sum_ += i
    return sum_

回答by Senthil Kumaran

You are returning the sum from within the for loop. Indent it outside. Keep it at the same level of indentation as for.

您正在从 for 循环中返回总和。在外面缩进。保持与 for 相同的缩进级别。

回答by Nirmal Sudharman

You need to dedent the return statement so that it falls outside the loop:

您需要删除 return 语句,使其落在循环之外:

def addNumbers(num)
    sum=0
    for i in range(0,num+1)
        sum=sum+i
    return sum

回答by Manh Duc Tran

if anyone want to know how to add 0 + 1 count until 100. There is it!

如果有人想知道如何将 0 + 1 计数加到 100。就是这样!

  x = 0
    while x<100:
        x += 1
        print(x)