I am learning Python 3. As far as I know, the print() function in Python 3 return None
. I could find one website here that says the same thing.
In that case, when we apply the "and" operator between two print()
functions, it should print None
because None and None = None
. I tried this with various print functions and the results seem to have been very different from what I was expecting. Here are the results. I tested them in Microsoft Visual studio 2015
print(0) and print(0)
prints 0
.
print(0) and print(1)
prints 0
.
print(1) and print(0)
prints 1
.
print(1) and print(1)
prints 1
.
I tried this with the "or" operator and the results even more surprised me.
None or None
should return None
. Here are the results.
print(0) or print(0)
prints 0 0
.
print(0) or print(1)
prints 0 1
.
print(1) or print(0)
prints 1 0
.
print(1) or print(1)
prints 1 1
.
What is the reason behind such behaviour ? Shouldn't the "or" operator return just one value? Please help me out here.
The logical operator performs short-circuit evaluation.
That means for and
, the right-hand side os only evaluated if the left-hand side is "true". And for or
the right-hand side is not evaluated if the left-hand side is "true".
In Python the value None
is not "true", the right-hand side of the and
statements will not execute.
Similarly for the or
, since the left-hand side is not "true" the right-hand side will execute.
As for the output you get, it's the output of the print
function calls. With the and
you get the output from only the left-hand side print
calls, with or
you get the output from both calls.