Home > Mobile >  Python Add up numbers from 1 to N (WHILE LOOP) and keep adding - SOLVED
Python Add up numbers from 1 to N (WHILE LOOP) and keep adding - SOLVED

Time:01-20

SOLVED - code already edited. A second while had to be used inside the main one. I think it sounds pretty easy hehe sorry I just started learning to code. Thanks!

I'm trying to add up all the number from 1 to N and print the result and then keep asking the user to enter number till the number zero is entered. I can make it sum the numbers and end the while but can't make it keep asking for more numbers like this: https://pastebin.com/9pWDT6su

num = int(input('N: '))
while num != 0:
    sum = 0
    while num < 0:
        num = int(input('ERROR - N: '))
    while n > 0:
        sum = sum   num
        num = num - 1
    print('Sum: ', sum) 
    num = int(input('N: '))
print('END')

CodePudding user response:

Try this :

num = int(input('N: '))

while num != 0:
    sum=0
    while num > 0:
        sum = sum   num
        num = num - 1
    
    print('Sum: ', sum)
    num = int(input('N: '))
    
print('END')

If you want the sum of 1-n for all numbers remove sum=0 inside while

CodePudding user response:

Try this:

num = int(input('N: '))
sum_ = 0
while True:
   if num < 0:
       num = int(input('ERROR - N: '))
   elif num == 0:
       break
   else:
       sum_ = sum_   num
       print('Sum: ', sum_) 
       num = int(input('N: '))
  •  Tags:  
  • Related