J. C. J. C. - 4 months ago 27
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):
return True
except ValueError:
return False

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


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:

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