user2918356
user2918356

Reputation: 139

How to add up a variable?

I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.

n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
    n=input("Start now ")
    a+=1

Upvotes: 2

Views: 207

Answers (3)

shad0w_wa1k3r
shad0w_wa1k3r

Reputation: 13372

You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.

print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
    try:
        all_nums.append(int(num))
    except:
        if num != "stop":
            print("Please enter stop to quit")
    num = input("Enter number ").lower()

print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))

sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.

Upvotes: 1

jaj2610
jaj2610

Reputation: 19

In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.

http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output

Upvotes: 1

mrKelley
mrKelley

Reputation: 3524

Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)

n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
    n=input("Enter a number: ")
    try:
        a+=int(n)
    except:
        if n != "stop":
            print("I can't make that an integer!")

print("Your sum is", a)

Upvotes: 0

Related Questions