Basic Arithmetic and Operator Precedence
You'll use arithmetic operators constantly in Python. Consider the most common ones and how precedence determines evaluation order.
Main Operations
12345678a = 10 b = 3 print(a + b) # Addition print(a - b) # Subtraction print(a * b) # Multiplication print(a / b) # Division print(a ** b) # Exponentiation
Operator Precedence
When multiple operators appear, Python evaluates them in this order (highest β lowest among arithmetic):
**;- Unary
+and-(sign); *,/;+,-.
Parentheses always win and make intent explicit. Exponentiation ** is right-associative.
123456789print(2 + 3 * 4) # 14 (multiplication before addition) print((2 + 3) * 4) # 20 (parentheses change the order) # Exponentiation binds tighter than unary minus print(-3 ** 2) # -9 (equivalent to -(3 ** 2)) print((-3) ** 2) # 9 # Right-associative exponentiation print(2 ** 3 ** 2) # 512 (2 ** (3 ** 2))
- Prefer parentheses in anything nontrivial, readability > cleverness.
- Remember
/always yields a float (even if divisible).
1. What value will this code output?
2. Which expression evaluates to 64?
3. What value will this code output?
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you explain what right-associative means for exponentiation?
What happens if I divide by zero in Python?
Can you give more examples of operator precedence?
Awesome!
Completion rate improved to 5.26
Basic Arithmetic and Operator Precedence
Swipe to show menu
You'll use arithmetic operators constantly in Python. Consider the most common ones and how precedence determines evaluation order.
Main Operations
12345678a = 10 b = 3 print(a + b) # Addition print(a - b) # Subtraction print(a * b) # Multiplication print(a / b) # Division print(a ** b) # Exponentiation
Operator Precedence
When multiple operators appear, Python evaluates them in this order (highest β lowest among arithmetic):
**;- Unary
+and-(sign); *,/;+,-.
Parentheses always win and make intent explicit. Exponentiation ** is right-associative.
123456789print(2 + 3 * 4) # 14 (multiplication before addition) print((2 + 3) * 4) # 20 (parentheses change the order) # Exponentiation binds tighter than unary minus print(-3 ** 2) # -9 (equivalent to -(3 ** 2)) print((-3) ** 2) # 9 # Right-associative exponentiation print(2 ** 3 ** 2) # 512 (2 ** (3 ** 2))
- Prefer parentheses in anything nontrivial, readability > cleverness.
- Remember
/always yields a float (even if divisible).
1. What value will this code output?
2. Which expression evaluates to 64?
3. What value will this code output?
Thanks for your feedback!