Assuming you're using python2.x: I think a better way to do this is to get the input as raw_input
. Then you know it's a string:
r = raw_input("enter radius:") #raw_input always returns a string
The python3.x equivalent of the above statement is:
r = input("enter radius:") #input on python3.x always returns a string
Now, construct a float from that (or try to):
try:
radius = float(r)
except ValueError:
print "bad input"
Some further notes on python version compatibility
In python2.x, input(...)
is equivalent to eval(raw_input(...))
which means that you never know what you're going to get returned from it -- You could even get a SyntaxError
raised inside input
!
Warning about using input
on python2.x
As a side note, My proposed procedure makes your program safe from all sorts of attacks. Consider how bad a day it would be if a user put in:
__import__('os').remove('some/important/file')
instead of a number when prompted! If you're eval
ing that previous statement by using input
on python2.x, or by using eval
explicitly, you've just had some/important/file
deleted. Oops.