简体   繁体   中英

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. X should be 1,2,3,4,5. and start with Y as 0. Y = X + Y should give the sum of 1 through 5.

Requirement: I want to start y as 0 and want y to hold latest add_sum value.

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?

使用减少

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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