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:
result_with_parentheses = (5 + 3) * 2
print(result_with_parentheses)This will output 16.
When operators have the same precedence, Python evaluates them from left to right. For example, in 10 / 2 * 5, division and multiplication have the same precedence. Python will first perform 10 / 2, which is 5.0, and then multiply that by 5, resulting in 25.0.
result_left_to_right = 10 / 2 * 5
print(result_left_to_right)This will output 25.0.
While Python has a comprehensive list of operator precedence, for common arithmetic, remembering the PEMDAS/BODMAS order and using parentheses liberally for clarity is a great strategy for beginners. Don't be afraid to use parentheses even when the order is implied; it often makes your code easier for others (and your future self!) to understand.