I am trying to compare two strings
in python 3.6
and if they are not equal then print a message and exit. My current code is:
location = 'United States of America'
if location.lower() != 'united states of america' or location.lower() != 'usa':
print('Location was different = {}'.format(location.lower()))
sys.exit()
else:
#do something
But the above code is not able to match the two strings and even though they are equal, it enters the loop and prints that they are different. I know its some silly mistake that I am making but unable to figure it out.
In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal. Note: It is important to keep in mind that this comparison operator will return True if the the values are same but are of different data types.
The >= operator checks if one string is greater than or equal to another string. Since one of both conditions of the operator is true (both strings are equal), we got a value of True. In this article, we learned about the various operators you can use when checking the equality of strings in Python with examples.
It returns True if operands on either side are not equal to each other, and returns False if they are equal. Note: It is important to keep in mind that this comparison operator will return True if the the values are same but are of different data types. Attention geek!
You can use the not equal Python operator for formatted strings (f-strings), introduced in Python 3.6. To return an opposite boolean value, use the equal operator ==. Keep in mind that some fonts change != to look like ≠ !
Your condition:
if location.lower() != 'united states of america' or location.lower() != 'usa':
will never be False
, since location.lower()
can't be 2 different strings at the same time.
I suspect you want:
if location.lower() != 'united states of america' and location.lower() != 'usa':
You are looking for an AND condition instead of a OR condition in your if statement. If you change that you should be set
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With