L
L
love_energy2020-06-23 14:14:35
Python
love_energy, 2020-06-23 14:14:35

What is the priority of operations in this situation with None, is and !=?

Why and how does operator precedence work?

>>> (1 != (None is None))
False
>>> (1 != None) is None
False
>>> (1 != None is None)
True

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
werevolff, 2020-06-23
@love_energy

(1 != (None is None))
Before comparing 1 and the second expression, python evaluates the expression. i.e .:
1. (None is None) = True
2. 1 != True
https://docs.python.org/release/3.0.1/reference/da...

The Boolean type is a subtype of the integer type, and Boolean values ​​behave like the values ​​0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned , respectively.

In python3, type boolean is a subtype of integer and, accordingly, the values ​​0 and 1 are equal (but not identical) False and True respectively
(1 != None) is None
First, python must evaluate all values ​​in a comparison operation (not exactly a comparison, but about this later). 1 != None is a true expression (True). Accordingly, in the second step:
True is None
is - identity operator. That is, it compares not only the value, but also the data type. For example, the previous task:
1 is True
Out: False
, respectively, True: boolean, None: None The types are different, so there is no identity. False
(1 != None is None)
This example uses chaining. The entry is equivalent to
1 != None and None is None
Out: True
if you want to do an iterative comparison, write
(1 != None) is None
The precedence of != and is should be the same, it's just that there is a lot of magic in Python, and with the above expression, the conversion indicated above is triggered.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question