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’,
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.