[英]Sum of numbers from 1 to 5 in loop
为了简化我的场景,我在这里重新定义我的问题。
我想在循环中添加从 1 到 5 的数字。 X 应该是 1,2,3,4,5。 并以 Y 为 0 开始。 Y = X + Y 应给出 1 到 5 的总和。
要求:我想将 y 开始为 0 并希望 y 保持最新的 add_sum 值。
预期输出:
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
我是 python 编码的新手,有人可以帮我吗?
使用减少
reduce(lambda x, y: x + y, range(6))
正如评论中提到的,修复你的语法并运行你的代码似乎工作得很好。
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()
如果您希望 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'
编辑:根据评论中的要求向代码添加评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.