J. C. J. C. - 21 days ago 6
Python Question

ValueError exception not working in python

I'm trying to make a simple program that will calculate the area of a circle when I input the radius. When I input a number it works, but when I input something else I'd like it to say "That's not a number" and let me try again instead of giving me an error.

I can't figure out why this is not working.

from math import pi

def get_area(r):
area = pi * (r**2)
print "A= %d" % area

def is_number(number):
try:
float(number)
return True
except ValueError:
return False

loop = True
while loop == True:
radius = input("Enter circle radius:")
if is_number(radius) == True:
get_area(radius)
loop = False
else:
print "That's not a number!"

Answer

When you don't input a number, the error is thrown by input itself which is not in the scope of your try/except. You can simply discard the is_number function altogether which is quite redundant and put the print statement in the except block:

try:
    radius = input("Enter circle radius:")
except (ValueError, NameError):
    print "That's not a number!"
get_area(radius)
Comments