Grundlæggende Aritmetik og Operatorpræcedens
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?
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Fantastisk!
Completion rate forbedret til 3.45
Grundlæggende Aritmetik og Operatorpræcedens
Stryg for at vise menuen
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?
Tak for dine kommentarer!