0

this might be a noob question, but could someone help me with this? I need to make sure the input is strictly a float. My current code returns an error, no matter what type of input.

    pricePerCandy = float(input('Please enter the price per candy (2 decimal places): '))
    if pricePerCandy.isalpha() or pricePerCandy.isalnum():
        print("Please enter the price with 2 decimal places.")
        pricePerCandy = float(input('Please enter the price per candy (2 decimal places): '))
Excelize
  • 9
  • 3
  • 2
    Python will report an `ValueError` if it cannot be converted into float. You can use the `try` to handle the exception – nu11p01n73R May 12 '15 at 06:41
  • We know that, the question is how I can make sure it gets entered as a float. – Excelize May 12 '15 at 06:42
  • Take a look at [Asking the user for input until they give a valid response](http://stackoverflow.com/q/23294658/4014959) – PM 2Ring May 12 '15 at 06:46
  • 1
    You convert your input to a `float` in the first line. In the second line you try to use the string methods `isalpha` and `isalnum` on your floating point value. That's not going to work. – Matthias May 12 '15 at 07:02

3 Answers3

5

You can write a simple function to read input until a float value is enterd by the user

>>> def readFloat():
...     while True:
...             try:
...                     value = float(input("Enter value "))
...                     return value
...             except ValueError:
...                     print "Please enter the price with 2 decimal places"

Test

>>> readFloat()
Enter value "asdf"
Please enter the price with 2 decimal places
Enter value "qwer"
Please enter the price with 2 decimal places
Enter value 1.2
1.2
nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
1

How about this?

import re

x = input('Please enter the price per candy (2 decimal places): ')

while True:
   if not re.match(r"^-?\d+.\d{2}$", x):
       x = input('Please enter the price per candy (2 decimal places): ')
       continue
   else:
      print("OK")
      break

If you don't need exactly 2 decimal places, you can change it to re.match(r"^-?\d+.\d{1,}$", x)

Alex Boklin
  • 91
  • 2
  • 6
0

Once you have validated that it can get converted to a float, then focus on if this have a decimal point and at least 2 numeric occurrences after that point, something like this (no regular expression)

def read():
while True:
    try:
        value = input("Enter value ")
        value_f = float(value)
        return value
    except ValueError:
        print "Please enter a valid float"


value=str(read())
point_position= value.find('.')
length_ = len(value)

required_decimal_positions = 2

if point_position>-1: 
    if point_position <= length_-(required_decimal_positions+1): # == if only a 2 decimal positions number is valid
        print "Valid"
    else:
        print "No valid - No enough decimals"
else:
    print "No valid - No decimal point"
emecas
  • 1,586
  • 3
  • 27
  • 43