2

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.

3
  • 1
    Just one comment from my end: if you expected boolean, then do return bool(val1 and val2) instead of return val1 and val2. Commented Aug 12, 2012 at 9:06
  • It's actually returning value from the variable rather than a boolean value. But thanks though. Commented Aug 12, 2012 at 9:13
  • Good. Good luck in learning Python. Commented Aug 12, 2012 at 16:47

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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)

1 Comment

I kind of knew this already but in my case the val1 and val2 contains value instead of boolean values like val1 = "hello" val2 = "world" if True else '' But I see what's causing this. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.