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.
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 :
any(range(4))evaluates toTrue, as therange(4)object contains non-zero integer values which evaluate toTrue(as opposed to arange(0)object, which would evaluate toFalseas it is an empty sequence orrange(1)since it contains only a zero integer value). For more on this, see Python docs on truth value testingTruevalue is then being compared toint(user_input). This is an integer comparison, which is comparing the booleanTruevalue as if it were an integer value (which, it technically is, sinceboolis a subclass ofint).int(True)evaluates to1, meaning the comparison fails for any user input not equal to"1".and, this causes the entire if-statement to fail, dumping you into the else-clause.I suspect you intended to check if the
user_inputvalue is between 0 and 4. The correct way to do this would be with theinkeyword, rather than theanyfunction :