Reputation: 21
I am trying to fix this code but I keep getting the same Value Error:
value = (input('Please enter number: '))
total = 0
sum = 0
while value == value:
count = float(input('Please enter another number: '))
sum =+ (1)
total = count + count
if count == (''):
break
average = (total+value/sum)
print(float(average))
Upvotes: 1
Views: 356
Reputation: 56
Working code with exception handling:
value = ""
while True:
try:
value = float(input('Please enter number: '))
break
except:
print("Invalid number")
total = 0
sum = 1 # It is 1 if including the first value, can be change to 0 if isn't
while value == value:
try:
count = input('Please enter another number: ')
count = float(count)
sum =+ (1)
total = total + count # Changed this line as OP asking for average
except ValueError:
if count == (''):
break
else:
print("Invalid number, press enter to exit loop.")
average = (total+value/sum)
print(float(average))
Upvotes: 0
Reputation: 161
Simply you can check weather the input is a number or not
value = (input('Please enter number: '))
total = 0
sum = 0
while value.isnumeric():
second_input = input('Please enter another number: ')
if not second_input.isnumeric():
break
count = float(second_input)
sum =+ (1)
total = count + count
average = (total+value/sum)
print(float(average))
Upvotes: 0
Reputation: 2660
You can try just using a try and catch statement to handle a possible ValueError:
try:
count = float(input('Please enter another number: '))
except ValueError:
break
However, I do think it's worth noting that there are other parts of your code that are incorrect, so if you could give a bit more depth into what exactly you are trying to code, we can help you fix other parts if you need it.
Upvotes: 0
Reputation: 14849
You are immediately trying to cast your input to a float
, which fails when something other than a number is entered. You could fix this by checking for a blank input before doing the cast:
...
count = input('Please enter another number: ')
if count == (''):
break
count = float(count)
...
You do have a number of other logical errors in your code at this point, but that should at least get you past the value error.
Upvotes: 1