How to arrange the priority order of python operators

小老鼠
Release: 2023-12-18 15:24:03
Original
7259 people have browsed it

The priority order of Python operators from high to low is as follows: brackets "()", power operation "**", positive and negative signs ", -", multiplication and division "*, /, //, %", addition and subtraction " ", comparison operators "<, >, <=, >=, ==, !=", logical not "not", logical AND "and", logical or "or ". In actual use, parentheses can be used to change the precedence of operators.

How to arrange the priority order of python operators

The operating system for this tutorial: Windows 10 system, Python version 3.11.4, Dell G3 computer.

The order of precedence of Python operators from high to low is as follows:

  1. Brackets ()

  2. Power operation**

  3. Positive and negative signs, -

  4. Multiplication and division*, /, //, %

  5. # #Addition and subtraction

  6. Comparison operators<, >, <=, >=, ==, !=

  7. Logical not

  8. logical and and

  9. logical or or

In actual use, You can use parentheses to change the precedence of operators.

Detailed introduction

1. Brackets: The expression within the brackets has the highest priority.

python

print(1 + 2 * 3)  # 输出结果为 5  
print((1 + 2) * 3)  # 输出结果为 9
Copy after login
2. Exponential operator: **

python

print(2 ** 3)  # 输出结果为 8
Copy after login
3. Positive and negative signs: - and (note the positive and negative here Signs are different from addition and subtraction operations because they do not change the priority of addition and subtraction operations)

python


print(-2)  # 输出结果为 -2  
print(+2)  # 输出结果为 2
Copy after login
4. Multiplication, division, modulo: *, /, %

5. Addition and subtraction: , -

6. Comparison operators: <, <=, >, >=, !=, ==

7. Bitwise operators: & (bitwise AND), | (bitwise OR), ^ (bitwise exclusive OR)

8. Logical operators: not, or, and (note, Python’s Logical operations are from left to right, so the priority of not is higher than and, and the priority of and is higher than or)

9. Identity operator: is, is not

10. Member operation Operators: in, not in

It is useful to remember these precedences, especially when you need to combine multiple operators. For example, if you want to take modulo a number and then add 1, you should use parentheses to ensure that the addition is performed before modulo.

The above is the detailed content of How to arrange the priority order of python operators. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template