Precedence and Associativity of Operators in Python

These exercises donโ€™t require advanced logic โ€” just practice writing and evaluating expressions correctly based on precedence.


1) Simple Arithmetic with Precedence

Compute and print the result of:

3 + 4 * 5

2) Use Parentheses to Change Order

Evaluate:

(3 + 4) * 5

and print the result.


3) Division and Multiplication

Write and print:

100 / 5 * 2

4) Power vs. Multiply

Compute and print:

2**3 * 4

5) Mixed Operators

Evaluate:


6) Modulus with Add

Print the result of:


7) Using Floor Division

Evaluate and print:


8) Associativity with Subtraction

Compute:

and explain why the result is that number.


9) Associativity with Division

Compute:


10) Combination

Evaluate:


11) Relational Precedence

Compare:

and print the Boolean result.


12) Logical With Arithmetic

Evaluate:


13) Logical with Arithmetic and Parentheses

Evaluate:


14) Mixed Relational

Print the result of:


15) Boolean Precedence

Evaluate and print:


16) Parentheses in Boolean

Re-write #15 with parentheses to change result:


17) Combined Arithmetic + Boolean

Evaluate:


18) Compare Equal & Not Equal

Print:


19) Ternary Operator

Use ternary expression to print:

for x = 7.


20) Nested Arithmetic & Bitwise

Evaluate:

and explain why that result occurs.


๐Ÿง  Concepts Practiced

Grammar
Example

Precedence

* / % before + -

Power

** highest among arithmetic

Associativity

Left-to-right for + - * /, right-to-left for **

Relational

< > == !=

Logical

not > and > or

Ternary

X if C else Y


๐Ÿ“Œ Early Evaluation Rules (Simplified)

  1. Parentheses

  2. Exponentiation

  3. Multiply, Divide, Mod, Floor Div

  4. Add, Subtract

  5. Relational

  6. Logical (not > and > or)


๐Ÿ€„ Quick Example


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated