python

Arithmetic Operations in Python


Arithmetic operations are the basic operations we perform on numbers. Python supports various arithmetic operators for different mathematical calculations.

 

Arithmetic Operators

  1. Addition ('+')
  2. Subtraction(' - ')
  3. Multiplication(' * ')
  4. Division(' / ')
  5. Floor Division(' // ')
  6. Modulus(' % ')
  7. Exponentiation(' ** ')

 

Addition (' + ')

The addition operator adds two numbers.

Example:

a = 10
b = 5
result = a + b
print(result)  # Output: 15
 

 

Subtraction(' - ')

The subtraction operator subtracts the second number from the first number.

Example:

a = 10
b = 5
result = a - b
print(result)  # Output: 5

 

 

Multiplication(' * ')

The multiplication operator multiplies two numbers.

Example:

a = 10
b = 5
result = a * b
print(result)  # Output: 50

 

 

Division(' / ')

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

 

 

Floor Division(' // ')

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

 

 

Modulus(' % ')

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

 

 

Exponentiation(' ** ')

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

 

 

Using Arithmetic Operators with Different Data Types

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)

 


python