Abascus
Abascus

Reputation: 127

What does the expression "print(1) and print("0") return in python?

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.

Upvotes: 2

Views: 2743

Answers (2)

Amadan
Amadan

Reputation: 198446

"Returning" and "printing" are different things. print will always return None and print whatever you give it, if called. The thing that surprises you is the behaviour of Boolean operators, not print.

x or y is defined as "The value of x if truthy; else, the value of y".

x and y is defined as "The value of x if falsy; else, the value of y".

Crucially, y is not evaluated if x fits the operator's criterion. This is called short-circuiting, and is pretty unique to and and or operators.

Now, None is a falsy value; thus None and y will never evaluate y, while None or y will always evaluate y. This is the reason why your print(...) and print(...) prints one value (the second print isn't executed because of short-circuiting), and why print(...) or print(...) prints two (both need to be evaluated to determine the result of and, as no short-circuiting is possible).

Upvotes: 5

Some programmer dude
Some programmer dude

Reputation: 409404

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.

Upvotes: 3

Related Questions