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 doesn't != work for string index comparison?

I tried to run this code with input "AC039"

 code = input("Enter code: ").upper()
 if code[0] != ('N' or 'A' or 'C' ):
     print("The first character must be N, A or C")
else:
    print("Pass!")

It gave me the output error result:

The first character must be N, A or C

However, if I input "AC039" into the below code using ‘not in’,

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

code = input("Enter code: ").upper()
if code[0] not in ["N", "A", "C"]:
    print("The first character must be N, A or C")
else:
    print("Pass!")

The resulting output is:

print("Pass!")

Why doesn’t "!=" work for the first set of code, since both code[0] and ‘A’ are string types?

I ran a check using type function on code[0] and it returned string type.

code = input("Enter code: ").upper()
print(type(code[0]))
print(type('A'))

returns:

<class 'str'>
<class 'str'>

>Solution :

It’s because the "or" operator compares sequentially.
from the given input "AC039",

code[0] != ('N' or 'A' or 'C' ):

what’s happening from the above code is, comparing one by one.

(code[0] != 'N') -> True
(code[0] != 'A') -> False
(code[0] != 'C') -> True

since the first ‘N’ doesn’t match with ‘A’, it stops going through other comparisons, ‘A’ and ‘C’.

print('N' != ('N' or 'A' or 'C' )) -> False
print('A' != ('N' or 'A' or 'C' )) -> True
print('C' != ('N' or 'A' or 'C' )) -> True

However, if code[0] not in ["N", "A", "C"]: works because "not in" checks whole elements in the array.

I hope it helps.

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