Reputation: 330
My original bit of python was:
if i.count('<') and i.count('>') == (0 or 1):
pass
else:
print('error')
This passes with i = '<>' and fails with i = '<>>' which is what I want. However it also fails with i = '' which I don't want and can't understand.
In ipython3 i've fiddled with this long enough to come down to the abstracted
0 == (0 or 1)
which strangely returns False. I'm guessing it has something to do with 0=False 1=True, but even after quite a bit of googleing it still doesn't quite make sense to me.
Do I really have to rewrite my original code to the much longer and to my mind uglier:
(i.count('<') and i.count('>') == 0) or (i.count('<') and i.count('>') == 1)
Upvotes: 1
Views: 109
Reputation: 369334
0 or 1
is always evaluated to 1
(The expression x or y
first evaluates x
; if x
is true, its value is returned; otherwise, y
is evaluated and the resulting value is returned. -- from Boolean operations)
>>> 0 or 1
1
0 == (0 or 1)
is equivalent to 0 == 1
-> False
.
To check whether x is 0
or 1
, do the following:
x == 0 or x == 1
or
x in (0, 1)
Upvotes: 9