Home > Enterprise >  Python - How to simply limit a input that is a float?
Python - How to simply limit a input that is a float?

Time:10-05

I'm trying to do a limiter for my Python app(?). It's simple. Well, should be simple.

I want to limit the input to £0.09 to £5.67. I'm having trouble though. I've tried:

challenge1 = input('Please enter money: ',float(0.09, 5.67))
challenge1 = input('Please enter money: ',float(>0.08, <5.68))
challenge1 = input('Please enter money: ',float(>0.09, <=5.67))
challenge1 = input('Please enter money: ',float(math.max(0.09, math.min(5.67)))

But none of these work. Imported math too. And I would like it to be as simple as that if possible. No loops, if statements, etc..

Any help would be greatly appreciated.

Thanks.

CodePudding user response:

The simplest method, as I see it, is unfortunately a clean if statement.

if challenge1 > 0.09 and challenge1  < 5.67:
    #do something
else:
    print("Invalid")

I don't think there exists an option in input to limit it. If you want the code to look cleaner, you can wrap this code into a function and call it as one line.

def Limit(challenge1):
    if challenge1 > 0.09 and challenge1  < 5.67:
        #do something
    else:
        print("Invalid")

someValue = input()
Limit(someValue)

CodePudding user response:

You could do something like this to avoid an explicit if but you'll need a while loop:

while 0.09 < (value := float(input('Please enter money: '))) < 5.67:
    print(value)

Thus all/any values entered that can be converted to float and are within the specified range will be printed. Invalid values will raise ValueError. Out of range values will break the loop

  • Related