Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Short-circuiting with helper function in print()

Can someone please explain why the following code comes out as "geeks" in the console?

def check():
    return "geeks"

print(0 or check() or 1)

I’m assuming that Python recognizes the boolean operator, thus treating 0 == False?

So does that mean every time boolean operators are used, the arguments are treated as True/False values?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The reason that "geeks" will be printed is that or is defined as follows:

The Python or operator returns the first object that evaluates to true
or the last object in the expression, regardless of its truth value.

When check() returns the string "geeks", that value evaluates to True because it is a non-empty string. That value is then the first term in the or expression that evaluates to True, so that value is the result of the entire expression, and so is what gets printed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading