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.
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:
Brackets ()
Power operation**
Positive and negative signs, -
Multiplication and division*, /, //, %
- # #Addition and subtraction
- Comparison operators<, >, <=, >=, ==, !=
- Logical not
- logical and and
- 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!