Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use an accumulator in a while loop

Tags:

python

I am trying to write a program that takes input from the user and then multiplies that input by 10. This input is then added to an accumulator whose initial value is acc=0.0. This repeats until the acc reaches < 100. I am not sure if there are other ways to do it, but for now I want to use the while loop for this. Below is what I have done so far. But not quite there. I know Im having trouble digesting the while loop concept.

condition=100
number = input("Enter your number: ")
number = int(number)*10
acc=0.0
while acc <= condition:
    number1 = input("Next number: ")
    number1 = int(number1)*10
    acc = number1 + number
    print("The summed value is", acc)
like image 364
Mohamed Haroon Avatar asked Dec 14 '22 13:12

Mohamed Haroon


2 Answers

You are not really adding to the accumulator, in each iteration you are setting the accumulator to number1 + number. Do

acc = acc + number1

instead, or acc += number1, which is equivalent.

Also, you should almost never have variable names like number and number1, but that's another thing.

like image 175
maniexx Avatar answered Jan 01 '23 10:01

maniexx


Your mistake is in the accumulator assignment after taking number1 input. You keep assigning number and number1 to accumulator.

Here's the working code:

condition=100
number = input("Enter your number: ")
number = int(number)*10
acc = number
while acc <= condition:
        number1 = input("Next number: ")
        number1 = int(number1)*10
        acc = acc + number1
        print("The summed value is", acc)
like image 20
Ashycre Avatar answered Jan 01 '23 10:01

Ashycre