Rachit
Rachit

Reputation: 105

How to add previously calculated sum to new input?

I am making a flowchart sum. User can add as many numbers as he wants. The program takes a number, adds it to past result, and the process continues. But the problem is that the program is adding only three numbers. It is adding the first two entered numbers to the last entered number. I want it to store the loop sum somewhere so that when I enter a new number the result should be:

sum of first two numbers + third entered number(if any)+

fourth entered number(if any)+fifth entered number(if any)+.....

I have attached this flowchart diagram for convenience.

And here's my code for the same:

num1=int(input('Enter a number: '))
num2=int(input('Enter another number: '))
sum=num1+num2
count = 1
while count > 0 : 
    ask=input('Do you want to add 1 more number? y/n: ')
    if ask=='y':
       num3=int(input('Enter the number: '))
       res=num3+sum
       print('Your total till now:',res)
       count = count + 1
       res = res+sum
    elif ask=='n':
        print('Total=',sum)
    else:
        print('Please enter correct choice')

Upvotes: 1

Views: 344

Answers (1)

Grayrigel
Grayrigel

Reputation: 3594

Try this:

num1=int(input('Enter a number: '))
num2=int(input('Enter another number: '))
sum=num1+num2
count = 1
while count > 0 :
    ask=input('Do you want to add 1 more number? y/n: ')
    if ask=='y':
       num3=int(input('Enter the number: '))
       res=num3+sum
       print('Your total till now:',res)
       count = count + 1
       sum = res
       #res = res+sum
       continue
    elif ask=='n':
        print('Total=',sum)
    else:
        print('Please enter correct choice')

Output:

Enter a number: 2
Enter another number: 2
Do you want to add 1 more number? y/n: 'y'
Enter the number: 2
('Your total till now:', 6)
Do you want to add 1 more number? y/n: 'y'
Enter the number: 2
('Your total till now:', 8)
Do you want to add 1 more number? y/n: 'y'
Enter the number: 2
('Your total till now:', 10)
Do you want to add 1 more number? y/n: 'y'
Enter the number: 5
('Your total till now:', 15)

Upvotes: 1

Related Questions