python3 ValueError value

10,621

I think you misunderstand what ValueError (and in general, an Exception) is.

Exceptions are a way for a method to signal to its caller that some critical error condition has been encountered that would prevent that method from executing as intended. Python's try-except-finally control structure provides a way for the caller to detect those error conditions and react accordingly.

ValueError is a standard Exception raised by various methods that perform range-checking of some kind to signal that a value provided to the method fell outside the valid range. In other words, it's a universal way of signaling that error condition. ValueError by itself doesn't do any kind of checking. There are many other standard Exceptions like this; KeyError signifies that you tried to access a key in a mapping structure (like a dict or set) that didn't exist, IndexError means you tried to index into a list-like structure to an invalid location, etc. None of them actually do anything special in and of themselves, they're simply a way of directly specifying exactly what kind of problem was encountered by the called method.

Exceptions go hand in hand with the idiom in python that it is generally considered 'easier to ask forgiveness than permission'. Many languages support exceptions of course, but Python is one of the few where you will very frequently see code where the Exception case is actually a commonly-followed code path rather than one that only happens when something has gone really wrong.

Here is an example of the correct use of a ValueError:

def gen(selection):
    if imode == 0:
        # do EOS stuff here
    elif imode == 1:
        # do S2 stuff here
    else:
        raise ValueError("Please Select An Option Between 0-1")

def selector():
    while True:
        try:
            gen(int(input("Generate for EOS(0) or S2(1)")))
            break
        except ValueError as e: # This will actually satisfy two cases; If the user entered not a number, in which case int() raises, or if they entered a number out of bounds, in which chase gen() raises.
            print(e) 

Note there are probably much more direct ways to do what you want, but this is just serving as an example of how to correctly use a ValueError.

Share:
10,621
BaRud
Author by

BaRud

Updated on June 13, 2022

Comments

  • BaRud
    BaRud almost 2 years

    I am trying to write a function using python3, with exception handling. I thought ValueError is the right tool to check if the value is in given range, as given here in python3 doc which says:

    function receives an argument that has the right type but an inappropriate value

    So, in this my tiny snippet, I am expecting to use ValueError to check range(0-1) which is not doing:

    while True:
        try:
            imode = int(input("Generate for EOS(0) or S2(1)"))
        except (ValueError):
            print("Mode not recognised! Retry")
            continue
        else:
            break
    print(imode)
    

    which yeilds:

    Generate for EOS(0) or S2(1)3
    3
    

    Sure, I can do the value checking as:

    if (imode < 0 or imode > 1):
        print("Mode not recogised. RETRY!")
        continue
    else:
        break
    

    but the ValueError seems do do this thing.

    There are several question on ValueError here, but none of them checking "inappropriate value, e.g. this I am a novice and python is not my main language. Kindly give me some insight.

    • nbro
      nbro over 9 years
      What made you think that ValueError knows your range?
    • nbro
      nbro over 9 years
      Just use a normal check. Exceptions handlers are used where a normal check with the if construct is not enough. In your case is sufficient ;)
    • nbro
      nbro over 9 years
      But if you want to prevent conversion errors (you try to convert to int, but the user enters a char), then you should catch the ValueError exception!
    • nbro
      nbro over 9 years
      I recommend you to see more about exceptions and how to handle them, then you will understand better when to use them ;)