Reputation: 13
I'm writing for creating a list of number from input and get the average of the list. The requirement is: when the user enters a number, the number will be appended to the list; when the user press Enter
, the input section will stop and conduct and calculation section.
Here is my code:
n = (input("please input a number"))
numlist = []
while n != '':
numlist.append(float(n))
n = float(input("please input a number"))
N = 0
Sum = 0
for c in numlist:
N = N+1
Sum = Sum+c
Ave = Sum/N
print("there are",N,"numbers","the average is",Ave)
if I enter numbers, everything works fine. But when I press Enter
, it shows ValueError
. I know the problem is with float()
. How can I solve this?
Upvotes: 0
Views: 130
Reputation: 895
this should solve ur prob ,by adding a try,catch block around ur print statement
n = (input("please input a number"))
numlist = []
while True :
numlist.append(float(n))
#####cath the exception and break out of
try :
n = float(input("please input a number"))
except ValueError :
break
N = 0
Sum = 0
for c in numlist:
N = N+1
Sum = Sum+c
Ave = Sum/N
print("there are",N,"numbers","the average is",Ave)
Upvotes: -1
Reputation: 1077
You don't need the float()
around the input()
function inside your loop because you call float()
when you append n
to numlist
.
Upvotes: 2