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?
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?
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 evaluatesx
; ifx
is false, its value is returned; otherwise,y
is evaluated and the resulting value is returned.The expression
x or y
first evaluatesx
; ifx
is true, its value is returned; otherwise,y
is evaluated and the resulting value is returned.