Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 only contains a zero integer value).
  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. 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):
    ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading