The Python Oracle

can Python 'and' return None?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Question
00:36 Accepted answer (Score 2)
02:11 Answer 2 (Score 5)
02:30 Answer 3 (Score 2)
02:46 Answer 4 (Score 1)
03:33 Thank you

--

Full question
https://stackoverflow.com/questions/5410...

Accepted answer links:
[[Python 3]: Operator precedence]: https://docs.python.org/3/reference/expr...
[[Python 3]: Truth Value Testing]: https://docs.python.org/3/library/stdtyp...
[if]: https://docs.python.org/3/reference/comp...
[while]: https://docs.python.org/3/reference/comp...
[[Python 3]: class ]: https://docs.python.org/3/library/functi...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x

#avk47



ANSWER 1

Score 5


It means if a is Truthy and b is not None and not what you thought it meant i.e. a and b is Truthy

a = 999
b = None

if a and b is not None:
    print("a is True but b is None")
else:
    print("a is True and b is not None")



ANSWER 2

Score 2


The code above means:

If a (is truthy), AND b isn't None, then #do something.




ACCEPTED ANSWER

Score 2


According to [Python 3]: Operator precedence (emphasis is mine):

The following table summarizes the operator precedence in Python, from lowest precedence (least binding) to highest precedence (most binding).

...
and                                                 Boolean AND
not x                                               Boolean NOT
in, not in, is, is not, <, <=, >, >=, !=, ==        Comparisons, including membership tests and identity tests
...

The fact that is not comes after and, means that it will be evaluated before and (both might not be evaluated at all, due to lazy evaluation - thanks @NickA for the comment), so the expression is equivalent to (adding parentheses for clarity):

if a and (b is not None):

Also, according to [Python 3]: Truth Value Testing:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

your if statement is perfectly OK (produces a bool).

Examples (using [Python 3]: class bool([x])):

>>> bool(0)
False
>>> bool(100)
True
>>> bool([])
False
>>> bool([0])
True
>>> bool(None)
False
>>> bool({})
False
>>> bool({1: 1})
True
>>> bool(None is not None)
False
>>> bool(1 is not None)
True
>>> bool(2 and 1 is not None)
True



ANSWER 4

Score 1


In this code, you evaluate b is not None first, which is a boolean.

And then a is implicitly converted into a boolean (For a list/dict, False if it is empty. For a number, False if it is 0)

then and is evaluated which always return a boolean.