简体   繁体   中英

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.

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

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

The sum function will sum over any iterable (which includes range)

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 :

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 = 0
x = 3
for number in range(1000):
    if number%x == 0:
        result += number
print(result)

The best way is using filter and sum :

# any iterable variable
iterable_var = range(100)
res = sum(filter(lambda x: x % 3 == 0, iterable_var), 0)

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