When you start combining multiple operators in a single Python expression, you might wonder which operation happens first. This is where operator precedence comes into play. It's like a set of rules that dictates the order in which operations are evaluated in an expression. Understanding precedence is crucial for writing correct and predictable code. Python, like many programming languages and mathematics, follows a specific order of operations.
The general order of operations, often remembered by the acronym PEMDAS or BODMAS, is as follows:
graph TD
A[Parentheses (or Brackets)] --> B[Exponents (or Orders)]
B --> C[Multiplication and Division]
C --> D[Addition and Subtraction]
Let's break this down with Python's operators. In Python, parentheses () have the highest precedence. Any expression enclosed in parentheses is evaluated first. After parentheses, exponentiation ** is evaluated. Then, multiplication *, division /, floor division //, and modulo % are performed. These have the same precedence, so they are evaluated from left to right. Finally, addition + and subtraction - are evaluated, also from left to right. Other operators like bitwise operators, comparison operators, and logical operators have their own precedence levels, but for basic arithmetic, the above is the primary set to remember.
Consider this expression: 5 + 3 * 2. Without knowing precedence, you might think it's (5 + 3) * 2 = 16. However, because multiplication has higher precedence than addition, Python first calculates 3 * 2, which is 6, and then adds 5. So, the actual result is 5 + 6 = 11.
result = 5 + 3 * 2
print(result)The output will be 11.
Parentheses are your best friend when you want to explicitly control the order of operations or to make your code more readable. For example, if you truly wanted (5 + 3) * 2, you would write it like this: