The Python Oracle

Python - Shortcircuiting strange behaviour

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Popsicle Puzzles

--

Chapters
00:00 Python - Shortcircuiting Strange Behaviour
00:29 Answer 1 Score 0
00:50 Accepted Answer Score 8
01:25 Thank you

--

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

--

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

--

Tags
#python #shortcircuiting

#avk47



ACCEPTED ANSWER

Score 8


That's because f() and False is an expression (technically a single-expression statement) whereas a += 1 and False is an assignment statement. It actually resolves to a += (1 and False), and since 1 and False equals False and False is actually the integer 0, what happens is a += 0, a no-op.

(1 and True), however, evaluates to True (which is the integer 1), so a += 1 and True means a += 1.

(also note that Python's and and or always return the first of their operands that can unambiguously determine the result of the operatio)




ANSWER 2

Score 0


I believe that

a+=1 and False

is equivalent to

a+=(1 and False)

and

a+=1 and True

is equivalent to

a+=(1 and True)

For example:

In [15]: a = 0

In [16]: a+=2 and True

In [17]: a
Out[17]: 1