...

/

Arithmetic Operators in Python

Arithmetic Operators in Python

Learn about arithmetic operators and their usage in Python.

We'll cover the following...

There are different arithmetic operators that can be applied for mathematical operations: +, -, *, /, %, // and **.

Python 3.8
a = 4 / 2 # performs true division and yields a float 2.0
b = 7 % 2 # % yields remainder 1
c = 3 ** 4 # ** yields 3 raised to 4 (exponentiation)
d = 4 // 3 # // yields quotient 1 after discarding fractional part
print("4 / 2 =",a)
print("7 % 2 =",b)
print("3 ** 4 =",c)
print("4 // 3 =",d)

In-place assignment operators offer a good shortcut for arithmetic operations. They include +=, -=, *=, /=, %=, //= and **=.

Python 3.8
a = 2
b = 12
a **= 3 # same as a = a ** 3
b %= 10 # same as b = b % 10
print(a)
print(b)

Operation nuances

On performing floor division a // b, the result is the largest integer which is less than or equal to the quotient. The // operator is called a floor division operator.

Python 3.8
print(10 // 3) # yields 3
print(-10 // 3) # yields -4
print(10 // -3) # yields -4
print(-10 // -3) # yields 3
print(3 // 10) # yields 0
print(3 // -10) # yields -1
print(-3 // 10) # yields -1
print(-3 // -10) # yields 0

In the code above:

  • In -10 // 3, the multiple of 3 that yields -10 is -3.333, whose floor value is -4.
  • In 10 // -3, the multiple of -3 that yields 10 is -3.333, whose floor value is -4.
  • In -10 // -3, the multiple of -3 that yields -10 is 3.333, whose floor value is 3.

Note: The print() function is used for sending output to the screen.

Operation a % b is evaluated as a(b(a//b))a - (b * (a // b)) ...