shriek
shriek

Reputation: 5823

What does Python return when we return with logical operator?

I was reading someone else's code and he had something like this:

return val1 and val2 

I tried this in the Python interpreter and it gave me the latter value on AND while OR gives me the prior value.

So my question is what exactly is happening in that statement?

Thanks.

Upvotes: 2

Views: 235

Answers (2)

Simeon Visser
Simeon Visser

Reputation: 122336

An AND statement is equal to the second value if the first value is true. Otherwise it is equal to the first value.

An OR statement is equal to the first value if it is true, otherwise it is equal to the second value.

Note that in Python an object can be evaluated to a boolean value. So "bla" and False will evaluate to the second value because the first value is true (it is a non-empty string and bool("string") = True).

This is how boolean statements are evaluated in Python (and multiple other programming languages). For example:

  • True and False = False (equal to second value because the first value is true)
  • False and True = False (equal to the first value because the first value is not true)
  • True and True = True (equal to the second value because the first value is true)
  • True or False = True (equal to the first value because it is true)
  • False or True = True (equal to the second value)

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1121406

An expression using and or or short-circuits when it can determine that the expression will not evaluate to True or False based on the first operand, and returns the last evaluated value:

>>> 0 and 'string'
0
>>> 1 and 'string'
'string'
>>> 'string' or 10
'string'
>>> '' or 10
10

This 'side-effect' is often used in python code. Note that not does return a boolean value. See the python documentation on boolean operators for the details.

Upvotes: 11

Related Questions