Tuesday, 3 May 2016

python - A version of str.isdigit that returns True for decimal fractions?





I want to test raw_input to make sure that the string contains only numbers and at maximum a single decimal point. str.isdigit() looked promising but it will not return True if there is a decimal point in the string.



Ideally, the code would look like this:



def enter_number():

number = raw_input("Enter a number: ") # I enter 3.5
if number.SOMETHING: # SOMETHING is what I am looking for
float_1 = float(number)
return float_1
else
sys.exit()

half = enter_number() / 2 # = 1.75
double = enter_number() * 2 # = 7


Answer



I suggest the EAFP approach.



float raises the ValueError exception if its argument is not a valid float:



In [6]: float('bad value')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
in ()
----> 1 float('bad value')


ValueError: could not convert string to float: 'bad value'


You could catch it:



number = raw_input("Enter a number: ")
try:
return float(number)
except ValueError:

sys.exit()

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...