Python provides various arithmetic operators for performing basic mathematical operations. Below are the commonly used arithmetic operators in Python along with their detailed usage:
1. Addition Operator (<span>+</span>
)
Used to add two numbers or concatenate strings, lists, and other iterable objects.
print(3 + 5) # Output: 8 (adding numbers)
print("Hello" + " World") # Output: Hello World (string concatenation)
print([1, 2] + [3, 4]) # Output: [1, 2, 3, 4] (list concatenation)
2. Subtraction Operator (<span>-</span>
)
Used to subtract one number from another.
print(10 - 4) # Output: 6
3. Multiplication Operator (<span>*</span>
)
Used to multiply two numbers or repeat strings, lists, and other iterable objects.
print(3 * 5) # Output: 15 (multiplying numbers)
print("Hi" * 3) # Output: HiHiHi (string repetition)
print([1, 2] * 3) # Output: [1, 2, 1, 2, 1, 2] (list repetition)
4. Division Operator (<span>/</span>
)
Used to divide one number by another, resulting in a float.
print(10 / 2) # Output: 5.0
print(7 / 3) # Output: 2.3333333333333335
5. Floor Division Operator (<span>//</span>
)
Used to divide one number by another, resulting in an integer (rounded down).
print(10 // 3) # Output: 3
print(-10 // 3) # Output: -4 (rounded down)
6. Modulus Operator (<span>%</span>
)
Used to divide one number by another, returning the remainder.
print(10 % 3) # Output: 1
print(15 % 4) # Output: 3
7. Exponentiation Operator (<span>**</span>
)
Used to calculate the power of a number.
print(2 ** 3) # Output: 8 (2 raised to the power of 3)
print(3 ** 2) # Output: 9 (3 raised to the power of 2)
8. Assignment Operators Combined with Arithmetic Operators
Python supports combining arithmetic operators with assignment operators to simplify code.
a = 5
a += 3 # Equivalent to a = a + 3
print(a) # Output: 8
b = 10
b -= 4 # Equivalent to b = b - 4
print(b) # Output: 6
c = 2
c *= 3 # Equivalent to c = c * 3
print(c) # Output: 6
9. Operator Precedence
The precedence of arithmetic operators from highest to lowest is as follows:
-
** (exponentiation)
-
*, /, //, % (multiplication, division, floor division, modulus)
-
+, – (addition, subtraction)
Parentheses <span>()</span>
can be used to change the order of operations.
print(2 + 3 * 4) # Output: 14 (multiplication before addition)
print((2 + 3) * 4) # Output: 20 (addition before multiplication)
10. Special Usage
-
Floating Point Arithmetic: Python supports floating point arithmetic, but care must be taken with floating point precision issues.
print(0.1 + 0.2) # Output: 0.30000000000000004
-
Complex Number Arithmetic: Python supports complex number arithmetic.
print((1 + 2j) * (3 + 4j)) # Output: (-5+10j)
Conclusion
The arithmetic operators in Python are powerful and flexible, capable of meeting various mathematical operation needs. Mastering the usage and precedence of these operators can help developers write more efficient and concise code.