What is (1 or 2) and (1 and 2) mean in Python?
I was writing python. I'm sick of those repetitive or
sentences. This is juat an example.
for i in range(10):
if i == 1 or i == 2:
print(i)
I suddenly thought of novices often make mistakes like if i == 1 or 2
. It always return True
because the 2
. Then why not bracket it! So I tried this:
for i in range(10):
if i == (1 or 2):
print(i)
I thought I would get a syntax error, but I got this:
1
Why I only got 1
, where was the number 2
?
I changed (1 or 2)
to (2 or 1)
, then I got 2
this time. Next I changed it to (1 and 2)
. I guess it doesn't make sense logically, but it outputed 2
. and
always outputs the last number, or
outputs the first one.
>>>print(1 or 2)
1
>>>print(1 and 2)
2
>>>print(1 or 2 or 3)
1
>>>print(1 and 2 and 3)
3
>>>print(1 or 2 and 3)
1
>>>print(1 and 2 or 3)
2
So, how did these fantastic results come about? What did they mean?