Arithmetic operators in python

Published: March 21, 2019

DMCA.com Protection Status

Arithmetic is a branch of mathematics that consists of the study of numbers. In python, there are three main type of numbers:

(1) integer numbers

 >>> x = 2
 >>> type(x)
  <class 'int'>

(2) real numbers (float)

>>> x = 3.1415
>>> type(x)
<class 'float'>

(3) complex numbers (complex)

>>> z = 1+2j
>>> type(z)
<class 'complex'>

An operator is a symbol, a letter or even a word, used to do an operation between two numbers. Let's see the arithmetic operators in python through several simple examples:

Operator addition +

The addition of two integers gives an integer, example:

>>> 3 + 2
5

The addition of a float and an integer gives a float, example:

>>> 2.1 + 3
5.1

The addition of two floats give a float, example:

>>> 4.3 + 2.1
6.4

The addition of an integer and a complex number, gives a complex number example:

>>> x = 2
>>> z = 1 + 2j
>>> x + z
(3+2j)

The addition of two complex numbers gives a complex number, example:

>>> z1 = 1 + 2j
>>> z2 = 2 + 5j
>>> z1 + z2
(3+7j)

Operator subtraction -

The subtraction of an integer from an integer, gives an integer example:

>>> 3 - 2
1

The subtraction of n integer from a float, gives a float example:

>>> 2.1 - 3
-0.8999999999999999

The subtraction of a float from a float, gives a float example:

>>> 4.3 - 2.1
2.1999999999999997

The subtraction of a integer number from a complex number, gives a complex number example:

>>> z = 1 + 2j
>>> z - 1
2j

The subtraction of a complex number from a complex number, gives a complex number example:

>>> z1 = 1 + 2j
>>> z2 = 2 + 5j
>>> z1 - z2
(-1-3j)

Operator multiplication *

Si on multiplie deux entiers en python on obtient un entier, exemple:

 >>> 3 * 2
6

Si on multiplie un réel et un enitier en python on obtient un réel, exemple:

>>> 2.1 * 3
6.300000000000001

Si on multiplie deux réels en python on obtient un réel, exemple:

>>> 4.3 * 2.1
9.03

Si on multiplie deux nombres complexes en python on obtient un complexe, exemple:

>>> z1 = 1 + 2j
>>> z2 = 2 + 5j
>>> z1 * z2
(-8+9j)
>>>

Operator division /

To divide a number by another there is the / operator, example:

>>> 4 / 2
2.0

with two floats:

>>> 7.0 / 3.2
2.1875

with a complex number

>>> z = 1 + 2j
>>> z / 2
(0.5+1j)

with two complex numbers

>>> z1 = 1 + 2j
>>> z2 = 2 + 3j
>>> z1 / z2
(0.6153846153846154+0.07692307692307691j)

Operator power **

To raise a number to the power of another number, there is the ** operator

>>> 3**2
9

since 3 * 3 = 8

>>> 3**3
27

since 3 * 3 * 3 = 27

with floats:

>>> 7.0 / 3.2
2.1875

with a complex number

>>> z = 1 + 2j
>>> z ** 2
(-3+4j)

with z1 ** z2

>>> z1 = 1 + 2j
>>> z2 = 2 + 3j
>>> z1**z2
(-0.015132672422722659-0.179867483913335j)

Remainder of the Euclidean division

>>> 5 % 3
2

since 5 = 1 * 3 + 2

Quotient of the Euclidean division

>>> 5 // 3
1

since 5 = 1 * 3 + 2

References