Python Programming Tutorial - Precedence and Associativity
Precedence and Associativity in Python Programming
Understanding Operator Precedence
- The tutorial introduces the concept of precedence and associativity in Python programming, starting with an example involving basic arithmetic operations.
- An example is provided: adding 2 and 5 (resulting in 7) and then multiplying by 4. The expected result is 28, but the actual output is incorrect due to operator precedence rules.
- It is explained that multiplication (*) has a higher precedence than addition (+), leading to the evaluation of the expression as (2 + (5 * 4)), resulting in an answer of 22 instead of the anticipated 28.
Precedence Chart Overview
- A precedence chart outlines various operators ranked by priority:
- Parentheses have the highest priority.
- Exponential operator follows next.
- Unary operators come third, followed by multiplication/division/modulus (* / // %).
- Addition/subtraction (+ -) are fifth, while bitwise operators follow thereafter.
- The tutorial emphasizes that parentheses can be used to alter default precedence; for instance, using (2 + 5) * 4 correctly yields an answer of 28.
Associativity Rules Explained
- When multiple operators share the same precedence level, associativity rules dictate how expressions are evaluated. For example, in the expression
2 + 5 - 1, both + and - have equal precedence.