-1

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?

pfan
  • 31
  • 6
  • 1
    what is `geeks`? There's no way to answer your question without knowing what `geeks` is, and just the code you show here will produce `NameError: name 'geeks' is not defined`. – CryptoFool Sep 24 '22 at 19:23
  • @CryptoFool `geeks` is just a string. I'd made the correction. – pfan Sep 24 '22 at 19:33
  • Every time you use `or`, you're asking python to evaluate `True`/`False` conditions. So, it needs to treat them as Booleans. And it has nothing to do with the `print` function. Whatever you pass as argument to `print` is going to be evaluated before printing. Then `0 or "geeks" or 1` is "geeks" (see suggested duplicate) and therefore the print statement can be reduced to `print("geeks")` – Ignatius Reilly Sep 24 '22 at 19:33

1 Answers1

1

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.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44
  • The question to the above answer was "does 0 always evaluate to `False`". I deleted it by accident. – pfan Sep 24 '22 at 19:38
  • 1
    yes, that's correct. Any empty collection evaluates to False as well. Any non-empty collection evaluates to True. A string is a collection of characters, so an empty string evaluates to False and a non-empty string evaluates to True. Note that here, "evaluates to" is only talking about what happens to determine how an expression with boolean operators is evaluated. What's more correct is to say that any expression is either "truthy" or "non-truthy", because as you can see by this example, the "geeks" string in the end gets "evaluated" as a string. So a non-empty string is always "truthy". – CryptoFool Sep 24 '22 at 19:41