简体   繁体   中英

Effect of “and” on assignment and addition

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

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

In Python and and or do not return boolean values, but rather return one of the options presented to them which evaluates to the correct boolean value.

For example, and will return either the first False value it encounters, or the last True value:

>>> 1 and 3
3

>>> 1 and 0
0

Similarly, or will return the first True value it encounters, and otherwise return the first False value:

>>> 2 or 3
2

>>> 0 or 2
2

>>> False or 0
0

Basically, you should keep in mind that and and or do not necessarily return True / False , but return one of the elements presented to them which evaluates to True or False .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM