Definition
What is 2 + 3 × 4 to Python: 20 or 14?
An operator is a symbol that performs an operation on values. An expression combines values, variables and operators into something Python can evaluate to a single value. Python has arithmetic, assignment, comparison and logical operators, evaluated in a fixed order of precedence.
In simple words
Python follows the same order as school maths: brackets first, then powers, then multiply and divide, then add and subtract. So 2 + 3 * 4 is 14. Comparisons such as 5 > 3 give True or False, and 'and', 'or' and 'not' combine those answers.
Why it matters
Every calculation in a program, from a shopping bill to a model's error, is an expression. Getting the order right avoids silent bugs where the program runs but gives the wrong number.
How it works
| Operator | Meaning | Example | Result |
|---|---|---|---|
| + - * | Add, subtract, multiply | 6 * 7 | 42 |
| / | Divide (always a float) | 7 / 2 | 3.5 |
| // | Whole-number division | 7 // 2 | 3 |
| % | Remainder | 7 % 2 | 1 |
| ** | Power | 2 ** 3 | 8 |
| == != < > | Compare | 5 > 3 | True |
| and or not | Combine True/False | True and False | False |
In code
A bill with quantity, discount and a free-delivery check.
price = 120
quantity = 3
discount_percent = 10
subtotal = price * quantity
discount = subtotal * discount_percent / 100
total = subtotal - discount
print("Subtotal:", subtotal)
print("Discount:", discount)
print("Total:", total)
free_delivery = total >= 300 and quantity >= 2
print("Free delivery?", free_delivery)
print("2 + 3 * 4 =", 2 + 3 * 4)
print("(2 + 3) * 4 =", (2 + 3) * 4)
print("17 // 5 =", 17 // 5, "and 17 % 5 =", 17 % 5)Output
Subtotal: 360 Discount: 36.0 Total: 324.0 Free delivery? True 2 + 3 * 4 = 14 (2 + 3) * 4 = 20 17 // 5 = 3 and 17 % 5 = 2
Try it yourself
Predict the result
Work out each expression in Python's order, then match it to its value.
- 2 + 3 * 4
- (2 + 3) * 4
- 10 // 3
- 10 % 3
- 2 ** 4
- 5 > 3 and 2 > 4
Common mistakes
- Using = when you mean ==.
- Forgetting that * happens before +. Use brackets when in doubt.
- Confusing / and //: 7 / 2 is 3.5 but 7 // 2 is 3.
Check yourself
Summary
- Expressions combine values with operators into one value.
- Precedence: brackets, powers, * / // %, then + -.
- Comparisons give True or False; and, or, not combine them.
Finished reading?
Sources: Python docs: Operator precedence