Possible Duplicate:
OR behaviour in python:
Probably extremely basic, but I'm a bit stuck after searching around. To me, this line of code should result in it printing "ELSE" as the string does not contain either word. Obviously it's not that simple and can't seem to figure out why. I've made sure to split the string in to a list just to make things easier to search. What am I doing wrong?
string = "Johnny Was Here Yesterday"
string = string.split()
if "Bob" or "Hello" in string:
print "IF"
else:
print "ELSE"
The proper way is to do this:
if 'Bob' in text or 'Hello' in text:
print 'IF'
else:
print 'ELSE'
The reason your code doesn't work is because Python evaluates that as:
if ('Bob') or ('Hello' in text):
Because 'Bob' always evaluates to True, your function always prints 'IF'
By the way, it's not good to use str or string as a variable name, as it overwrites the very useful builtin method str() or the library string.
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