Excelize
Excelize

Reputation: 9

Making sure input is a float

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): '))

Upvotes: 0

Views: 2161

Answers (3)

emecas
emecas

Reputation: 1586

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"

Upvotes: 0

Alex Boklin
Alex Boklin

Reputation: 91

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)

Upvotes: 1

nu11p01n73R
nu11p01n73R

Reputation: 26667

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

Upvotes: 5

Related Questions