-2

If you look at this:-

>>>a = "hello"
>>>b = "world"
>>>print a and b 
world
>>>print b and a
hello

and this:-

>>>a = "hello"
>>>b = "world"
>>>print a or b 
hello
>>>print b or a
world

Both are almost similar. So how are they different?

confused
  • 47
  • 1
  • 1
  • 3

1 Answers1

3

The or and and operators short-circuit. They return early when the outcome is a given.

For or that means that if the first expression is True, then there is no point in looking at the second expression as it doesn't matter:

>>> 'a' or 'b'
'a'
>>> False or 'b'
'b'

The same goes for and, but only when the first value evaluates to False; in that case the expression is always going to evaluate to False whatever the second expression is going to come to:

>>> False and 'b'
False
>>> 'a' and 'b'
'b'

See Boolean expressions:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343