简体   繁体   English

循环中从 1 到 5 的数字总和

[英]Sum of numbers from 1 to 5 in loop

To simplify my scenario, I am redefining my question here.为了简化我的场景,我在这里重新定义我的问题。

I want to add numbers from 1 to 5 in loop.我想在循环中添加从 1 到 5 的数字。 X should be 1,2,3,4,5. X 应该是 1,2,3,4,5。 and start with Y as 0. Y = X + Y should give the sum of 1 through 5.并以 Y 为 0 开始。 Y = X + Y 应给出 1 到 5 的总和。

Requirement: I want to start y as 0 and want y to hold latest add_sum value.要求:我想将 y 开始为 0 并希望 y 保持最新的 add_sum 值。

Expected output:预期输出:

    1st iteration: y = 1 (x = 1, y = 0)

    2st iteration: y = 3 (x = 2, y = 1)

    3st iteration: y = 6 (x = 3, y = 3)

    ...

    ...

    so on 

I am new to python coding, Can anyone help me for this?我是 python 编码的新手,有人可以帮我吗?

使用减少

reduce(lambda x, y: x + y, range(6))

As mentioned in the comments, fixing your syntax and running your code seems to work just fine.正如评论中提到的,修复你的语法并运行你的代码似乎工作得很好。

def read_num():
    for num in range (1,5):
        x = num
        add_sum(x)


def add_sum(x):
    global y
    y = x + y
        print ("y =", y)

y = 0
read_num()

If you want x to be 1 thru 5 inclusive , you have to use range(1,6) instead如果您希望 x 为 1 到 5包括在内,则必须使用range(1,6)代替

y = 0  # Assign value 0 to variable 'y'
for x in xrange(1, 6):  # Cycle from 1 to 5 and assign it to variable x using iterator as we need just 1 value at a time
  print '(x=%s, y=%s)' % (x, y)  # Display value of 'x' & 'y' variables to user for debug & learning purpose
  y += x  # Adding x to the y.
  print 'y=%s' % y  # Display result of sum accumulated in variable 'y'

Edit: added comments to the code as requested in comments.编辑:根据评论中的要求向代码添加评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM