Reputation: 139
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
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 list
s & do exactly as their name says. The str.lower()
method converts a string to lower-case completely.
Upvotes: 1
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
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