0

I was just fooling around in Python, and while I understand how the boolean logic works with 'True' or 'False'...I don't understand the results when you use other terms. For instance, if I type into Python:

"bear" and "dog"
"1 and 6"
"crab" or "food"

the output is:

'dog'
6
'crab'

Why? I didn't assign either of those variables to 'True' or 'False', so how does Python know which one to print out? How do you determine which is 'True', or which is 'False'?

Sorry if this is posted somewhere; I tried looking, but wasn't sure what the key terms were for this kind of question.

  • 1
    This is slightly more general, given the question. The underlying question is more "How does truthiness in Python work?" – zxq9 Nov 17 '15 at 23:14
  • @zxq9: I tried to pick a dupe that covers that aspect of the question. How's the "boolean 'and' in Python" one? – user2357112 Nov 17 '15 at 23:27
  • @user2357112 You know, it seems almost odd that there is not a canonical Q/A for that particular question -- just a few one-off questions (like this one and the one you referenced) where an answer requires touching on the subject, but never *explaining* it fully. – zxq9 Nov 17 '15 at 23:32
  • The 'boolean' one helped explain things in terms that I could understand! Thanks for finding that information for me! @user2357112 – WonkasWilly Nov 18 '15 at 05:37

1 Answers1

2

It's a bit of a special case you're looking at, here:

Normally, you wouldn't care about the actual value of a and b, but only whether it evaluates to True or not.

What happens here is that or returns the first value if that evaluates to True, and the second otherwise, so

if a or b:

actually runs if a exactly if a evaluates to True, and if b if it doesn't.

and works the other way around: If the first operand evaluates to True, return the second (a and b is True only if both evaluate to True), else return the first.

This is really handy if you have a statement that should only be executed when another thing is False, ie.

function_that_might_return_false_on_error() or die_horribly()
Marcus Müller
  • 34,677
  • 4
  • 53
  • 94