plast1cd0nk3y
plast1cd0nk3y

Reputation: 418

Constructing a While loop in a function to check if user input falls between two float values

I am constructing a function that will take one argument (a value). That value will be converted to a float in order to check if it exists between two bounds (which are also float values). If the user input value does not land between the bounds, continue to ask the user for an input value.

def check(value):
    value = float(value)
    while -10.0 > value < 1.5:
        value = raw_input("False. Please enter a number:")
    else:
        return True

When I run the code with a value that does not exist between the bounds, the math still evaluates to True (expected the user to be prompted again for an input, ie expected False).

>>> check(-11)
True

Also I apologize for any weird formatting for the codes above (when I copied and pasted them here, I couldn't figure out how to have the whole block of code appear together).

EDIT:

So before I saw the other answers, I re-wrote some code; I also realized that my syntax was wrong in the code I posted so I have changed it accordingly in the new code. Here is an answer I have now come up with (I would also appreciate some feedback on the new solution I have): def check(value):

value = float(value)

if -10.0 < value < 1.5:
    return True

while not -10.0 < value < 1.5:
    value = float(raw_input("False. Please enter a number:"))

Upvotes: 0

Views: 712

Answers (1)

blhsing
blhsing

Reputation: 106552

A number can never be both less than -10.0 and greater than 1.5, so the while condition will also be False and the loop would always end immediately. Since no break occurs during the loop, the else block will always be executed, therefore always returning True.

You should use the or operator instead to check if the input is out of bounds:

while -10.0 > value or value > 1.5:
    value = float(raw_input("False. Please enter a number:"))

Upvotes: 1

Related Questions