0

I want to validate a float value between 0 and 5 that can have the format x.xx

So 3.14 is valid, however 3.14a would be invalid.

if x <= 0 or x > 5 or not x.isdigit():
    return 'error'

However, this will return error for 1.1, since there's the '.' character...

Apollo
  • 8,874
  • 32
  • 104
  • 192

6 Answers6

3
def is_valid(num):
    try:
        return 0 < float(num) <= 5
    except ValueError:
        print('error: not a valid floating point number')
        return False

float will raise a ValueError if num is not a number which can be interpreted as float.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • I have added a `try`/`except` block to handle the case you mention. Please feel free to roll back the edit if you do not agree with or like that modification – Cory Kramer Jun 03 '15 at 14:18
  • Since I don't think that returning `'error'` is a great error handling way exactly I'd have left the exception in place and leave the correct error handling up to the caller... but it illustrates the point better. – deceze Jun 03 '15 at 14:19
2

You can use a regex:

import re

validate = lambda x: re.match(r"^[0-4]\.[0-9]{2}|5\.00$", x) is not None
x = "1.21"

if not validate(x):
    print('error')

This will match a string containing a number with the y.xx format, where y is in the 0-4 range and y can be any. This covers the 0.00-4.99 range. Finally, we cover 5.00 as a special case.

If you need to accept 4.0 as well, you can slightly modify the regex as

r"^[0-4]\.[0-9]{1,2}|5\.00?$"

so that the second digit becomes optional.

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
1
x = "3.14a"
try:
    if float(x) <= 0 or float(x) > 5:
        print('error')
except:
    print('error')

I think isinstance will solve your problem

Aleksander Monk
  • 2,787
  • 2
  • 18
  • 31
1
def is_string_a_float_between_0_and_5(s):
    try:
        return 0 <= float(s) <= 5
    except ValueError:
        return False
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
0

Convert your string to a float. If it fails that test then you know you don't have a number. If it converts, then you can check if it is between 0 and 5:

x = '3.14'
try:
    x = float(x)
except ValueError:
    return 'error'

if x <= 0 or x > 5:
    return 'error'

If x is '3.14a' then it will hit the ValueError and return 'error'

Andy
  • 49,085
  • 60
  • 166
  • 233
0

You're missing a bit of information here. Are you expecting that x is a string? If that's the case, you need to cast x to a float before testing if it's between 0 and 5.

Secondly, it's considered "non-pythonic" to check your variable types. Python is a "duck typed" language, and you're not supposed to check types unless absolutely necessary. Here's a great answer about if someone misuses your function.

To answer the real question about checking if a number is between 0 and 5:

y = float(x)  # Will throw exception if x is not castable to a float
if y < 0 or y > 5:
    raise ValueError("Bad x parameter!")
adveres
  • 1
  • 2