0

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?

Clay Hsu
  • 1
  • 1
  • `or` only needs one of the terms to be `True`, so it will always return the _first_ `True` element - in your examples it will always return `1`. On the other hand `and` needs all terms to be `True` so it will always return the _last_ one if they are all `True`, or the _first_ `False` one: try `1 and 0 and 2` – gimix Nov 26 '22 at 13:23
  • That's called **lazy** condition in Python. In case `a and b`, if a is false, its value is returned. Otherwise, b is evaluated and the value is returned. In case `a or b`, if a is true, its value is returned. Otherwise, b is evaluated and the value is returned. That's reason why if `i == (1 or 2)` true, it always returns 1. – GenZ Nov 26 '22 at 13:57

0 Answers0