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 :
- The statement
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 only contains a zero integer value). - This
Truevalue is then being compared toint(user_input). This is an integer comparison, which is comparing the booleanTruevalue as if it were an integer value.int(True)evaluates to1, meaning the comparison fails for any user input not equal to"1". - 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):
...