2

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
vaultah
  • 44,105
  • 12
  • 114
  • 143
adamcircle
  • 694
  • 1
  • 10
  • 26

1 Answers1

3

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)
<ipython-input-6-dc9476bbdbf8> in <module>()
----> 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()
Community
  • 1
  • 1
vaultah
  • 44,105
  • 12
  • 114
  • 143