Arithmetic operations are the basic operations we perform on numbers. Python supports various arithmetic operators for different mathematical calculations.
The addition operator adds two numbers.
Example:
a = 10
b = 5
result = a + b
print(result) # Output: 15
The subtraction operator subtracts the second number from the first number.
Example:
a = 10
b = 5
result = a - b
print(result) # Output: 5
The multiplication operator multiplies two numbers.
Example:
a = 10
b = 5
result = a * b
print(result) # Output: 50
The division operator divides the first number by the second number. The result is a float.
Example:
a = 10
b = 5
result = a / b
print(result) # Output: 2.0
The floor division operator divides the first number by the second number and rounds down to the nearest whole number.
Example:
a = 10
b = 3
result = a // b
print(result) # Output: 3
The modulus operator returns the remainder of the division of the first number by the second number.
Example:
a = 10
b = 3
result = a % b
print(result) # Output: 1
The exponentiation operator raises the first number to the power of the second number.
Example:
a = 2
b = 3
result = a ** b
print(result) # Output: 8
Python's arithmetic operators can be used with different data types such as integers, floats, and complex numbers. The behavior of these operators may vary based on the data type.
Example with integers and floats:
int_num = 10
float_num = 3.5
# Addition
result = int_num + float_num
print(result) # Output: 13.5
# Subtraction
result = int_num - float_num
print(result) # Output: 6.5
# Multiplication
result = int_num * float_num
print(result) # Output: 35.0
# Division
result = int_num / float_num
print(result) # Output: 2.857142857142857
Example with complex numbers:
complex_num1 = 2 + 3j
complex_num2 = 1 + 2j
# Addition
result = complex_num1 + complex_num2
print(result) # Output: (3+5j)
# Subtraction
result = complex_num1 - complex_num2
print(result) # Output: (1+1j)
# Multiplication
result = complex_num1 * complex_num2
print(result) # Output: (-4+7j)
# Division
result = complex_num1 / complex_num2
print(result) # Output: (1.6-0.2j)