How to validate if a user input is both a float and with a given range in Python?
<p>I'm trying to validate a user input to check if it is both a number (float) and within a range (0-1).  I have used Try except to check if the input is a float as below:</p>

<pre><code>while True:
    try:
        rate=input(": ")
        rate=float(rate)
        break
    except ValueError:
        print("That was not a valid numerical value, please try again")
</code></pre>

<p>This works for checking if the input is numerical (floats are accepted) however I cannot make it check both if its numerical and within a range (0,1) this needs to return the rate to my main code.</p>

<p>I am able to validate if an input is within a range I just can't work out how to do both checks so that for example if a user enters 3.8 they get and error message and are able to re-input if they then put a string it would not crash the code.</p>

<p>You can consider using <code>try-except-else</code> in the following manner:</p>

<pre><code>min_val = 1
max_val = 10
while True:
    rate = input(": ")
    try:
        rate = float(rate)
    except ValueError:
        print("That was not a valid numerical value, please try again")
    else:
        if min_val &lt; rate &lt; max_val:
            break
        else:
            print("This number is not in the required range")
</code></pre>

<p>This will require the input to be a number in the range <code>min_val &lt; rate &lt; max_val</code>. Note that the <code>else</code> block is executed only if no <code>exception</code> was raised.</p>

<p>Another approach would be to use the already catched <code>ValueError</code> to raise your own:</p>

<pre><code>min_val = 1
max_val = 10
while True:
    rate = input(": ")
    try:
        rate = float(rate)
        if not min_val &lt; rate &lt; max_val:
            raise ValueError
    except ValueError:
        print("That was not a valid numerical value, please try again")
    else:
        break
</code></pre>

python python-3.x