Home >Backend Development >Python Tutorial >How does Python's logical operator precedence differ from C and C ?

How does Python's logical operator precedence differ from C and C ?

DDD
DDDOriginal
2024-11-11 15:21:03251browse

How does Python's logical operator precedence differ from C and C  ?

Precedence of Logical Operators (NOT, AND, OR) in Python

Contrary to C and C where precedence of logical operators follows the sequence NOT > AND > OR, Python's precedence may seem confusing.

Clarification

In Python, the precedence sequence for logical operators is actually:

NOT > AND > OR

This means that NOT has higher precedence than AND, while AND has higher precedence than OR.

Precedence Table

For a comprehensive understanding of operator precedence in Python, here is the complete precedence table:

Precedence Operator
0 :=
1 lambda
2 if - else
3 or
4 and
5 not x
6 in, not in, is, is not, <, <=, >, >=, !=, ==
7
8 ^
9 &
10 <<, >>
11 , -
12 *, @, /, //, %
13 x, -x, ~x
14 **, await x
15 x[index], x[index:index], x(arguments...), x.attribute
16 (expressions...), [expressions...], {key: value...}, {expressions...}

Example

Consider the following expression:

x = not (a or b) and c

Using the precedence table, we evaluate the expression as follows:

  1. Evaluate a or b, which results in True.
  2. Apply not to True, resulting in False.
  3. Evaluate c, which may result in either True or False.
  4. Apply and to False and c. Since one operand is False, the result is False.

The above is the detailed content of How does Python's logical operator precedence differ from C and C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn