Saturday, 30 September 2017

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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...