Pexlu
Pexlu

Reputation: 13

Python loop task with countless number additioning

I want to make easy program with loop but can't find out how. I am absolute beginner. So basicly program should add all numbers person writes to it. For example:

Person writes: 5

Program shows: 5

Person writes: 6

Program shows: 11

Person writes: 3

Program shows: 14 

and so on. This is what I did and it's wrong I don't know how to write it right.

while True:
    var1 = int(input("Write a number"))
    var2 = 0 + var1
    print(var2)

Upvotes: 0

Views: 161

Answers (4)

raymelfrancisco
raymelfrancisco

Reputation: 871

You should initialize your sum holder (var1) outside the loop and in order to update the sum holder, you should add the newest input to it.

>>> var1 = 0
>>> while True:
...    var1 += int( input('Write a number: ') )
...    print(var1)
...

Write a number: 1
1
Write a number: 2
3
Write a number: 4
7
Write a number: -6
1

Upvotes: 0

omri_saadon
omri_saadon

Reputation: 10621

This is the code you are looking for, when the user insert a non digit input, i'm printing bad input and the user can try again.

good luck!

total = 0
while True:
    try:
        user_input = int(input("enter number"))
    except ValueError:
        print ("bad input, try again")      # in case of the input is not a number
        continue
    total += int(user_input)
    print (total)

Upvotes: 3

Laszlowaty
Laszlowaty

Reputation: 1323

userInput = None # this variable will handle input from user
numberSum = 0 # this is sum of all your numbers
print("Type 'exit' to quit")
while True:
    userInput = input("Enter your number") # here you are taking numbers from user
    if userInput == 'exit': # if user enters 'exit' instead of number, program will call break
        break # break ends loop
    numberSum += int(userInput) # this will add int(userInput) to your numberSum. int() function
                # makes integer type from your String. You have to use it, because
                # while getting input() from user, it's considered as string
print("Your sum is: ")
print(numberSum) # printing your sum
print("byebye...")

Note, if you type anything else than 'exit' or number, the program will exit with ValueError

Upvotes: 1

The6thSense
The6thSense

Reputation: 8335

In your program each and every time you are updating var2 value with var1 value so the user input is printed

What you have to do is add the value var1 with var2 value .Initially var2 value is zero so it is equated to var1 and so on

var2=0
while True:

    var1 = int(input("Write a number"))

    var2 += var1

    print(var2)

Upvotes: 0

Related Questions