[英]I want to find the sum of the number which i have
I have some code where I must find the multiples of number 3 and then summarize them I have done the first job, I mean I found all the multiples of number 3 with for loop but I can't summarize all the numbers which I found. 我有一些代码,我必须找到3号的倍数,然后总结它们我已经完成了第一个工作,我的意思是我找到了3号循环的所有倍数,但是我无法总结我找到的所有数字。
I have tried so many times and tried to find the solution on google, but could not find 我已经尝试了很多次,并试图在谷歌上找到解决方案,但找不到
x = 3
for number in range(1000):
if number%x == 0:
print(number)
I need now the sum of all the numbers which indicates on this code, when you run this code you can see that there is publishing only the numbers that can divide by 3 now I need the sum of them 我现在需要这个代码上显示的所有数字的总和,当你运行这段代码时,你可以看到只发布了可以除以3的数字,现在我需要它们的总和
It's easier than you think: 它比你想象的容易:
sum(range(0, 1000, 3))
Explanation: 说明:
range
is defined as such: range([start], end[, step])
so range(0, 1000, 3)
means go from 0 to 1000 in steps of 3 range
定义如下: range([start], end[, step])
因此range(0, 1000, 3)
表示从0到1000以3为步长
The sum
function will sum over any iterable (which includes range) sum
函数将对任何iterable(包括范围)求和
You need a variable to hold the sum (If you are in learning stage): 你需要一个变量来保存总和(如果你处于学习阶段):
x = 3
total = 0
for number in range(1000):
if number % x == 0:
print(number)
total += number # equivalent to: total = total + number
print(total)
Edit: 编辑:
To answer your comment use condition or condition
: 要回答您的评论,请使用condition or condition
:
x = 3
y = 5
total = 0
for number in range(10):
if number % x == 0 or number % y == 0:
print(number)
total += number # equivalent to: total = total + number
print(total)
You could create a result
variable to which you can keep adding: 您可以创建一个可以继续添加的result
变量:
result = 0
x = 3
for number in range(1000):
if number%x == 0:
result += number
print(result)
The best way is using filter
and sum
: 最好的方法是使用filter
和sum
:
# any iterable variable
iterable_var = range(100)
res = sum(filter(lambda x: x % 3 == 0, iterable_var), 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.