0

If you do a try in python, and the code doesn't fail, but it's outside of a range you want or something, what is the best way to make it fail so it goes to the except?

A simple example is as follows, to check the input is a number between 0 and 1:

input = 0.2
try:
    if 0 < float( input ) < 1:
        print "Valid input"
    else:
        "fail"+0  (to make the code go to except)
except:
    print "Invalid input"

Is there a better way to go about this? The between range is just an example, so it should work with other things too (also, in the above example, it should also be able to use a number in string format, so detecting the type wouldn't really work).

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Peter
  • 3,186
  • 3
  • 26
  • 59

4 Answers4

3

Sorry but rchang's answer is not reliable for production code (assert statements are skipped if Python is run with the -O flag). The correct solution is to raise a ValueError, ie:

try:
    if 0 < float(input) < 1:
        raise ValueError("invalid input value")
    print "Valid input"
except (TypeError, ValueError):
    print "Invalid input"
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • Hmm, are you totally sure? I just tried it with Maya which creates the .pyo file and it still seemed to work correctly. – Peter Jan 12 '15 at 15:23
  • Ahh nvm, just noticed the other comment with a link to another post and it appears to be true, weird that it doesn't do that in Maya :p – Peter Jan 12 '15 at 15:30
  • @Peter: more exactly (sorry wrong wording), assert statements are skipped when Python is run with the '-O' flag. – bruno desthuilliers Jan 12 '15 at 15:33
1

You can use the raise statement:

try:
    if (some condition):
        Exception
except:
    ...

Note that Exception can be more specific, like for example, a ValueError, or maybe it can be an exception defined by you:

class MyException(Exception):
    pass

try:
    if (some condition):
        raise MyException
except MyException:
    ...
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
1

The other answer is accurate. But to educate you more about exception handling ... you could use raise.

Also consider Bruno's comment where he says:

You also want to catch TypeError in case input is neither a string nor a number.

Thus in this case we may add another except block

input = 1.2
try:
    if 0 < float( input ) < 1:
        print "Valid input"
    else:
        raise ValueError  #(to make the code go to except)
except ValueError:
    print "Input Out of Range"
except TypeError:
    print "Input NaN"

TypeError will be raised iff the input is an object ( for e.g)

Community
  • 1
  • 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
0

The built-in assertion mechanism may be a fit here.

input = 0.2
try:
    assert 0 < float( input ) < 1
    print "Valid input"
except (AssertionError, ValueError):
    print "Invalid input"

AssertionError will be raised if the condition you provide to the assert statement does not evaluate to True. Also, upon attempting the float conversion upon an invalid value would raise the ValueError.

rchang
  • 5,150
  • 1
  • 15
  • 25
  • Thanks haha, with what I'm after this seems perfect, I'd not heard of assert before but it seems really useful. – Peter Jan 12 '15 at 15:03
  • 1
    `assert` statements are deactived in .pyo files, they are for developers only. – bruno desthuilliers Jan 12 '15 at 15:11
  • 3
    Assertions are only meant for debugging and testing purposes, not for actual application logic. If you compile the Python code with optimizations, the `assert`statements are removed. Please see [the Python 3.4.2 doc](https://docs.python.org/3/reference/simple_stmts.html#grammar-token-assert_stmt) and [this SO answer](http://stackoverflow.com/a/1838411/1388240) for details. Better use exceptions for this, as shown in @brunodesthuilliers answer. – cyroxx Jan 12 '15 at 15:16
  • @brunodesthuilliers I learn things every day, it seems. Thanks for the course correction. – rchang Jan 12 '15 at 15:33
  • @rchang: we all learn things everyday... Or at least we should ;) – bruno desthuilliers Jan 12 '15 at 16:30