Logo

Developer learning path

Python

Operator Precedence in Python

Operator Precedence

85

#description

In Python, operator precedence determines the order in which operations are performed in an expression.

Like in mathematical expressions, Python has a specified order of precedence for its operators:

  1. Parentheses: Expressions inside parentheses are always evaluated first.
  1. Exponentiation: Exponential expressions are evaluated next.
  1. Multiplication, Division, and Modulus: These expressions are evaluated next, in the order of left to right.
  1. Addition and Subtraction: These expressions are evaluated next, in the order of left to right.
  1. Comparison Operators: These operators (e.g. <, >, <=, >=) compare the values of two expressions and provide a Boolean value as output.
  1. Logical Operators: These operators (e.g. and, or, not) evaluate Boolean expressions and provide a Boolean value as output.
  1. Assignment Operators: These operators (e.g. =, +=, -=) are used to assign values to variables.

For example, in the expression (4 + 5) * 2, the parentheses are evaluated first, resulting in 9 * 2, which equals 18. Similarly, in the expression 2 * 3 + 4, the multiplication is evaluated first, resulting in 6 + 4, which equals 10.

It is important to understand operator precedence in Python in order to avoid errors and ensure that expressions are evaluated correctly. It can also be useful to use parentheses to explicitly indicate the order of operations when expressions become more complex.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.