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 **
.
Press + to interact
a = 4 / 2 # performs true division and yields a float 2.0b = 7 % 2 # % yields remainder 1c = 3 ** 4 # ** yields 3 raised to 4 (exponentiation)d = 4 // 3 # // yields quotient 1 after discarding fractional partprint("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 **=
.
Press + to interact
a = 2b = 12a **= 3 # same as a = a ** 3b %= 10 # same as b = b % 10print(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.
Press + to interact
print(10 // 3) # yields 3print(-10 // 3) # yields -4print(10 // -3) # yields -4print(-10 // -3) # yields 3print(3 // 10) # yields 0print(3 // -10) # yields -1print(-3 // 10) # yields -1print(-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 is3
.
Note: The
print()
function is used for sending output to the screen.
Operation a % b
is evaluated as ...