Python - Shortcircuiting strange behaviour
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: Popsicle Puzzles
--
Chapters
00:00 Question
00:41 Accepted answer (Score 8)
01:28 Answer 2 (Score 0)
01:58 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
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Popsicle Puzzles
--
Chapters
00:00 Question
00:41 Accepted answer (Score 8)
01:28 Answer 2 (Score 0)
01:58 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