简体   繁体   中英

Write a program using while loop, which prints the sum of every fifth number from 0 to 500 (including both 0 and 500)

This is what I have done: Can anybody tell me where I went wrong?

num = 0
    x = 1
    while x <= 500:
        num += x
        x += 5

    print(num)

Your indentation is also wrong. It needs to be like this

num = 0
x = 0
while x <= 500:
        num += x
        x += 5
        print(num)

But, if you want to print only the final sum, you can use the print statement outside loop

num = 0
x = 0
while x <= 500:
        num += x
        x += 5
print(num)

Logic: We have to use while loop to check every number. We have to check whether the number is divisible by 5 or not, for that, we have to put if condition and keep on adding +1 to go from 0 to 500. If the condition is satisfied, add to to a variable whose initial value is 0. You code:

x=0
r=0
while x<=500:
    if x%5==0:
        r+=x
    x+=1
print(r)   

Or you can do it this way, start the initial value from 0, updating value of x should be 5, add it to variable whose initial value is 0. You alternative code:

x=0
r=0
while x<=500:
    r+=x
    x+=5
print(r)

The second code will help you rectify your personal code. Have a look

Yet another way:

x = 0
acc = 0
while (x := x + 5) <= 500:
    acc += x

Here we use an assignment operator inside while() to get the value while incrementing it at the same time.

it's simple using range(start, stop, step) with range(0, 500, 5) parameter as

# list of numbers
print([x for x in range(0, 501, 5)])

# sum of numbers
print(sum([x for x in range(0, 501, 5)]))

with while loop you can use := operator which is introduced in Python3.8 . it allows variable assignments within expressions.

total = 0
i = iter(range(5, 501, 5))
while val := next(i, None):
    if not val:
         break
    total += val

print('total : ', total)

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