Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effect of "and" on assignment and addition

Tags:

python

A line of code has tripped me up:

>>> i = 1
>>> j = 1
>>> i += j > 0 and i
>>> print(i)
 2

What is the underlying mechanic or system that makes this work? It seems like it's syntactic sugar for i = i + i if j > 0 else i, but that's a lot to unpack. Am I wrong? Is there another system in play I don't know?

Thanks!

EDIT:

For clarity:

>>> i = 3
>>> j = 2
>>> i += j > 1 and i
>>> i
6
like image 214
Noah Bogart Avatar asked Dec 25 '22 13:12

Noah Bogart


1 Answers

Let's break it down:

In [1]: i = 1

In [2]: j = 1

Now, let's look at the expression i += j > 0 and i:

In [3]: j > 0
Out[3]: True

Because j, which is 1 is greater than 0, this evaluates to True.

In [4]: j > 0 and i
Out[4]: 1

Because j > 0 is True, the value of the boolean expression is the value of the right-hand side, namely 1.

Thus, i += j > 0 and i simplifies to i += i or i = i + i:

In [5]: i += i

In [6]: i
Out[6]: 2

Let's also consider your second example:

>>> i = 3
>>> j = 2
>>> i += j > 1 and i
>>> i
6

For the thrid line we have these transforms:

i += j > 1 and i
i = i + (j > 1 and i)
i = 3 + (2 > 1 and 3)
i = 3 + (True and 3)
i = 3 + 3
i = 6
like image 104
Robᵩ Avatar answered Jan 10 '23 04:01

Robᵩ