Reputation: 15
I'm not sure whats wrong with the code as I'm only just starting out on python but when an erroneous value is typed in it outputs with "ValueError: could not convert string to float: '(Error value)'". However I would like it to output with "Invalid Character/s. Please Try Again." and then for the loop to continue back from the start, I wasn't able to figure out what I could change, so an explanation of what is required would be great as well.
ListOfNumbers = []
while True:
Number = float(input("Enter a number >>"))
if Number == 0:
print ("End.")
break
try:
ListOfNumbers.append(int(Number))
Average = float(sum(ListOfNumbers))/len(ListOfNumbers)
except ValueError:
print ("Invalid Character/s. Please Try Again.")
continue
print ("The total value is", sum(ListOfNumbers))
print ("The average value is", Average)
print ("The highest value is", max(ListOfNumbers))
print ("The lowest value is", min(ListOfNumbers))
ListOfNumbers.sort()
print ("List of numbers", ListOfNumbers)
Upvotes: 1
Views: 2402
Reputation: 1932
The ValueError
is exception is thrown by the line that takes in the input. Move the try
block to catch the exception.
while True:
try:
Number = float(input("Enter a number >>"))
if Number == 0:
print ("End.")
break
ListOfNumbers.append(int(Number))
Average = float(sum(ListOfNumbers))/len(ListOfNumbers)
except ValueError:
print ("Invalid Character/s. Please Try Again.")
continue
Upvotes: 1