pythonisnumeric

why does .isnumeric() work inconsistently, only with number 1 | Python 3


Hey I have encounter a problem writing my if-else function using .isnumeric(). in the following I wanted a different outcome depending on if the input is a number in the range of 4 or the letter w while also printing out an error if its none of the above. So, I first check if its numeric and if it’s in range.

user_input = input("type here: ")
if user_input.isnumeric() and int(user_input) == any(range(4)):
    print("do stuff 1")
elif user_input == "example":
    print("do stuff 2")
else:
    print("error")

but for some reason it only works with the number 1 for any other number like 0,2,3 it prints the error message. what am I missing? why does it only work on number 1.


Solution

  • The issue is not coming from str.isnumeric, but rather from the other condition you are checking in that same if-statement.
    What is happening is a bit complicated though, and to understand it you need to decompose the line :

    1. The statement any(range(4)) evaluates to True, as the range(4) object contains non-zero integer values which evaluate to True (as opposed to a range(0) object, which would evaluate to False as it is an empty sequence or range(1) since it contains only a zero integer value). For more on this, see Python docs on truth value testing
    2. This True value is then being compared to int(user_input). This is an integer comparison, which is comparing the boolean True value as if it were an integer value (which, it technically is, since bool is a subclass of int). int(True) evaluates to 1, meaning the comparison fails for any user input not equal to "1".
    3. Since you're using an and, this causes the entire if-statement to fail, dumping you into the else-clause.

    I suspect you intended to check if the user_input value is between 0 and 4. The correct way to do this would be with the in keyword, rather than the any function :

    if user_input.isnumeric() and int(user_input) in range(4):
        ...