Arithmetic operators are tools to perform basic math in Python. Think of them as shortcuts for calculations like adding, subtracting, or multiplying numbers.
Here are the main arithmetic operators in Python:
Operator | Symbol | Example | Result |
---|---|---|---|
Addition | + |
3 + 5 |
8 |
Subtraction | - |
10 - 4 |
6 |
Multiplication | * |
2 * 3 |
6 |
Division | / |
7 / 2 |
3.5 |
Floor Division | // |
7 // 2 |
3 |
Modulus | % |
7 % 2 |
1 |
Exponentiation | ** |
2 ** 3 |
8 |
The order of operations (PEMDAS)
When multiple operators are in one expression, Python follows the order of operations, or PEMDAS:
-
Parentheses
: Solve inside parentheses first.()
Example:2 * (3 + 5)
→2 * 8 = 16
. -
Exponents
: Solve powers next.**
Example:2 ** 3 * 4
→8 * 4 = 32
. -
Multiplication, Division
,*
,/
,//
: Perform these from left to right.%
Example:10 / 2 * 5
→5 * 5 = 25
. -
Addition, Subtraction
,+
: Perform these last, from left to right.-
Example:10 - 3 + 2
→7 + 2 = 9
.
Pro Tip:
Use parentheses to make your code clearer!
result = 2 + 3 * 4
# Without parentheses: Output = 14
result = (2 + 3) * 4
# With parentheses: Output = 20
Common mistakes and pitfalls
Mixing division types
Regular division /
print(4 / 2) # Output: 2.0 (not 2)
Floor division //
print(4 // 2) # Output: 2
Misunderstanding modulus %
%
The modulus operator gives the remainder, not the quotient.
print(7 % 3) # Output: 1 (7 divided by 3 has a remainder of 1)
Order of operations confusion
Forgetting the order of operations can lead to unexpected results.
result = 10 + 3 * 2 # Output: 16 (multiplication first)
result = (10 + 3) * 2 # Output: 26 (parentheses first)
Floating-point precision
Floating-point numbers might give surprising results due to how they’re stored:
print(0.1 + 0.2) # Output: 0.30000000000000004
Real-world use cases
Here are practical examples of arithmetic operators in action:
1. Budget Calculator
income = 3000
rent = 1200
food = 500
savings = income - (rent + food)
print("Savings:", savings)
2. Discount Application
original_price = 50
discount = 20 / 100 # 20%
final_price = original_price - (original_price * discount)
print("Final Price:", final_price)
Summary
- Arithmetic operators like
,+
,-
,*
,/
,//
, and%
are essential for calculations in Python.**
- Remember the order of operations (PEMDAS) to avoid mistakes.
- Use parentheses when in doubt to make your code clear.
- Test your understanding with real-world examples and practice exercises.