Grundläggande Aritmetik och Operatorprioritet
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?
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Fantastiskt!
Completion betyg förbättrat till 3.45
Grundläggande Aritmetik och Operatorprioritet
Svep för att visa menyn
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?
Tack för dina kommentarer!