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:
The reason your code doesn’t work is because Python evaluates that as:
Because
'Bob'always evaluates toTrue, your function always prints'IF'By the way, it’s not good to use
strorstringas a variable name, as it overwrites the very useful builtin methodstr()or the librarystring.