5

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.

1
  • of course it will enter it, 'United States of America'.lower() != 'usa' Commented Feb 22, 2018 at 9:42

2 Answers 2

10

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':
Sign up to request clarification or add additional context in comments.

1 Comment

even better: if location.lower() not in ('united states', 'usa'):
1

You are looking for an AND condition instead of a OR condition in your if statement. If you change that you should be set

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.