View Full Version : Use of "or"
Bharris
05-01-2009, 06:10 PM
I don't know why but I have never used or in any of my if statements, but I decided recently that I would try it to save some lines and have run into making it function.
Var = ("First", "Second", "Third")
for objs in Var:
if objs == "Second" | "Third":
print "Success"
here is the error that is thrown.
TypeError: unsupported operand type(s) for |: 'str' and 'str' #
I know someone here has to have an idea of how that works. thanks!
djTomServo
05-01-2009, 06:14 PM
I don't know why but I have never used or in any of my if statements, but I decided recently that I would try it to save some lines and have run into making it function.
Var = ("First", "Second", "Third")
for objs in Var:
if objs == "Second" | "Third":
print "Success"
here is the error that is thrown.
TypeError: unsupported operand type(s) for |: 'str' and 'str' #
I know someone here has to have an idea of how that works. thanks!
are you sure you're not meaning to use "||"?
Tim Rennie
05-01-2009, 09:27 PM
I think this is what you want:
for objs in Var:
if objs == "Second" or objs == "Third":
print "Success"
The | operator does exist, but it's a "bitwise or" for dealing with sequences of bits. "or" is the more normal "logical or".
The other issue is a bit subtler. If you write objs == "Second" or "Third" then Python interprets it as (objs == "Second") or ("Third")Since "Third" is a non-empty string it's considered to be always true, so your if statement would always execute! Writing it as (objs == "Second") or (objs == "Third") does the right thing, and the brackets can be dropped if you like.
Bharris
05-02-2009, 12:09 AM
I think this is what you want:
for objs in Var:
if objs == "Second" or objs == "Third":
print "Success"
The | operator does exist, but it's a "bitwise or" for dealing with sequences of bits. "or" is the more normal "logical or".
The other issue is a bit subtler. If you write objs == "Second" or "Third" then Python interprets it as (objs == "Second") or ("Third")Since "Third" is a non-empty string it's considered to be always true, so your if statement would always execute! Writing it as (objs == "Second") or (objs == "Third") does the right thing, and the brackets can be dropped if you like.
Ok. This is what I'm looking for. Thanks. This should be helpful.
Seth, you may be correct about what I was thinking. As I said I had never used it.
vBulletin® v3.7.1, Copyright ©2000-2010, Jelsoft Enterprises Ltd.