Python Forum

Full Version: Help with or operator
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm steaming fresh out of the oven new to Python and trying to teach it to myself using an online book. Based on the little I've learned, I'm trying to create a program that will ask the user to input their name and if the name is one of two names, it outputs one response. If the name isn't one of those names, it outputs a different response. For some reason, I'm only able to get one name to work (ie. if name = 'x' print), but when I try to add a second name using or (ie. if name = 'x' or 'y' print), then it just outputs whatever the user input rather than going to the else. Here's what I've got:

print('What is your name?')
myName = input()
if myName == 'Tom' or 'Jerry':
    print('Hello ' + myName)
else:
    print('Hello Stranger')
Am I not using the or operator correctly?
The if statement is not correct. Whatever the name is, the if condition evaluates to True.
In Python a non-empty string is True.

>>> myName = input()
Bob
>>> myName == 'Tom'
False
>>> bool(myName == 'Tom' or 'Jerry') # this one
True
>>> bool(False or True) # becomes this
True
So, what you want is:
if myName == 'Tom' or myName =='Jerry':
(May-31-2018, 06:04 PM)wavic Wrote: [ -> ]The if statement is not correct. Whatever the name is, the if condition evaluates to True.
In Python a non-empty string is True.

>>> myName = input()
Bob
>>> myName == 'Tom'
False
>>> bool(myName == 'Tom' or 'Jerry') # this one
True
>>> bool(False or True) # becomes this
True
So, what you want is:
if myName == 'Tom' or myName =='Jerry':

Thanks for the help! Do you mean to say that the or operator reads the statement as:
if [myName == 'Tom] or ['Jerry'=True]
And since 'Jerry' is a non-empty string, it is true, so it's always evaluating as True?

(May-31-2018, 06:03 PM)buran Wrote: [ -> ]https://python-forum.io/Thread-Multiple-...or-keyword
Thanks that was very helpful and also let's me know that this was a common enough problem that someone had to spell out the problem.
See my example in the previous post.
Every non-empty string is True.
>>> bool('Tom')
True
>>> bool('Victor')
True
So False or True is True. True or True is also True.

Whatever the name is, the if statement will be True.

myName == 'Tom' or 'Jerry' can be translate to (myName == 'Tom') or 'Jerry'. So it becomes False or True which is True or True or True which is also True.

Here is the example:
>>> myName = 'Vanessa'
>>> bool(myName == 'Tom' or 'Jerry')
True
Obviously myName is not Tom or Jerry but still this condition evaluates to True. Because 'Jerry' evaluates to True and the or operator.

Here you can see how all the logical operators work:
>>> True and False
False

>>> True and True
True

>>> False and True
False

>>> False or True
True

>>> False or False
False