4 Operators

Python includes different operators, allowing operations to be performed between operands, i.e., between variables, literals or expressions.

4.1 Arithmetic Operators

The basic arithmetic operators are integrated in Python.

We have already used some of them in the previous chapters to perform operations on integers or floating point numbers (addition, subtraction, etc.). Let’s take a quick look at the most common arithmetic operators used to perform operations on numbers.

4.1.1 Addition

An addition between two numbers is made using the + symbol:

print(1+1) # Addition
## 2

4.1.2 Subtraction

A subtraction between two numbers is performed using the - symbol:

print(1-1) # Subtraction
## 0

4.1.3 Multiplication

A multiplication between two numbers is performed using the * symbol:

print(2*2) # Multiplication
## 4

4.1.4 Division

A (real) division between two numbers is made using the symbol /:

print(3/2) # Division
## 1.5

To perform a Euclidean division (or division with remainder), slash is doubled:

print(3//2) # Euclidean division
## 1

4.1.5 Modulo

The modulo (remainder of the Euclidean division) is obtained using the symbol %:

print(12%10) # Modulo
## 2

4.1.6 Power

To raise a number to a given power, we use two stars (**):

print(2**3) # 2^3
## 8

4.1.7 Order

The order of operations follows the PEMDAS rule (Parentheses, Exponents, Multiplication and Division, Adition and Subtraction).

For example, the following instruction first performs the calculation \(2\times 2\), then adds \(1\):

## 5

The following instruction, using brackets, first calculates \(2+1\), then multiplies the result with \(2\):

## 6

4.1.8 Mathematical Operators on Strings

Some mathematical operators presented in Section 4.1 can be applied to strings.

When using the symbol + between two strings, Python concatenates these two strings (see Section 2.1.1) :

a = "euro"
b = "dollar"
## eurodollar

When a string is “multiplied” by a scalar \(n\), Python repeats this string \(n\) times:

## 'euroeuro'

4.1.9 Mathematical Operators on Lists or tuples

Some mathematical operators can also be applied to lists.

When using the symbol + between two lists, Python concatenates them into one:

l_1 = [1, "apple", 5, 7]
l_2 = [9, 11]
print(l_1 + l_2)
## [1, 'apple', 5, 7, 9, 11]

Same with tuples:

t_1 = (1, "apple", 5, 7)
t_2 = (9, 11)
print(t_1 + t_2)
## (1, 'apple', 5, 7, 9, 11)

By “multiplying” a list by a scalar \(n\), Python repeats this list \(n\) times:

## [1, 'apple', 5, 7, 1, 'apple', 5, 7, 1, 'apple', 5, 7]

Same with tuples:

## (1, 'apple', 5, 7, 1, 'apple', 5, 7, 1, 'apple', 5, 7)

4.2 Comparison Operators

Comparison operators allow objects of all basic types to be compared with each other. The result of a comparison test produces Boolean values.

Table 4.1: Comparison operators
Operator Python Operator Description
\(=\) == Equal to
\(\ne\) != (or <>) Different from
\(>\) > Greater than
\(\geq\) >= & Greater than or equal to
\(<\) < Lower than
\(\leq\) <= Less than or equal to
\(\in\) in In
\(\notin\) not in Not it

4.2.1 Equality, Inequality

To test the content equality between two objects:

a = "Hello"
b = "World"
c = "World"

print(a == c)
## False
print(b == c)
## True

The inequality between two objects:

x = [1,2,3]
y = [1,2,3]
z = [1,3,4]

print(x != y)
## False
print(x != z)
## True

4.2.2 Inferiority and Superiority, Strict or Broad

To know if an object is inferior (strictly or not) or inferior (strictly or not) to another:

x = 1
y = 1
z = 2

print(x < y)
## False
print(x <= y)
## True
print(x > z)
## False
print(x >= z)
## False

It is also possible to compare two strings. The comparison is carried out according to the lexicographical order:

m_1 = "eat"
m_2 = "eating"
m_3 = "drinking"
print(m_1 < m_2) # eat before eating?
## True
print(m_3 > m_1) # drinking after eat?
## False

When comparing two lists together, Python works step by step. Let’s look through an example to see how this comparison is done.

Let’s create two lists:

x = [1, 3, 5, 7]
y = [9, 11]

Python will start by comparing the first elements of each list (here, it is possible, the two elements are comparable; otherwise, an error would be returned):

print(x < y)
## True

As 1<9, Python returns True.

Let’s change x so that the first element is greater than the first element of y.

x = [10, 3, 5, 7]
y = [9, 11]
print(x < y)
## False

This time, as $10>$9, Python returns False.

Now let’s change the first element of x so that it is equal to y:

x = [10, 3, 5, 7]
y = [10, 11]
print(x < y)
## True

This time, Python compares the first element of x with that of y. As the two are identical, the second elements are compared. This can be demonstrated by evaluating the following code:

x = [10, 12, 5, 7]
y = [10, 11]
print(x < y)
## False

4.2.3 Inclusion and exclusion

As encountered several times in Chapter 3, the inclusion tests are performed using the operator in.

print(3 in [1,2, 3])
## True

To test if an item is excluded from a list, tuple, dictionary, etc., we use not in:

print(4 not in [1,2, 3])
## True
print(4 not in [1,2, 3, 4])
## False

With a dictionary:

dictionnaire = {"nom": "Rockwell", "prenom": "Criquette"}
"age" not in dictionnaire.keys()
## True

4.3 Logical operators

Logical operators operate on one or more logical objects (Boolean).

4.3.1 And logical

The and operator allows logical “AND” comparisons to be made. We compare two objects, x and y (these objects can result from a previous comparison, for this both only need to be Boolean).

If one of the two objects x and y is true, the logical “AND” comparison returns true:

x = True
y = True
print(x and y)
## True

If at least one of them is false, the logical “AND” comparison returns false:

x = True
y = False

print(x and y)
## False
print(y and y)
## False

If one of the two compared objects is equal to the empty value (None), then the logical “AND” comparison returns :

  • the value None if the other object is worth True or None
  • the value False if the other object is worth False.
x = True
y = False
z = None
print(x and z)
## None
print(y and z)
## False
print(z and z)
## None

4.3.2 Logical OR

The operator or allows logical “OR” comparisons to be made. Again, we compare two Booleans, x and y.

If at least one of the two objects x and y is true, the logical “OR” comparison returns true:

x = True
y = False
print(x or y)
## True

If both are false, the logical “OR” comparison returns false:

x = False
y = False
print(x or y)
## False

If one of the two objects is None, the logical “OR” comparison returns :

  • True if the other object is worth True
  • None if the other object is worth False or None.
x = True
y = False
z = None
print(x or z)
## True
print(y or z)
## None
print(z or z)
## None

4.3.3 Logical Not

The operator not, when applied to a Boolean, evaluates the latter at its opposite value:

x = True
y = False
print(not x)
## False
print(not y)
## True

When using the operator not on an empty value (None), Python returns True:

x = None
not x
## True

4.4 Some Functions

Python has many useful functions for manipulating structures and data. Table 4.2 lists some of them. Some require the loading of the math library, others require the statistics library. We will see other functions specific to the NumPy library in Chapter 9.

Table 4.2: Some numerical functions
Function Description
math.ceil(x) Smallest integer greater than or equal to x
math.copysign(x, y) Absolute value of x but with the sign of y
math.floor(x) Smallest integer less than or equal to x
math.round(x, ndigits) Rounded from x to ndigits decimal places
math.fabs(x) Absolute value of x
math.exp(x) Exponential of x
math.log(x) Natural logarithm of x (based on e)
math.log(x, b) Logarithm based on b of x
math.log10(x) Logarithm in base 10 of x
math.pow(x,y) x high to the power y
math.sqrt(x) Square root of x
math.fsum() Sum of the values of x
math.sin(x) Sine of x
math.cos(x) Cosine of x
math.tan(x) Tangent of x
math.asin(x) Arc-sineus of x
math.acos(x) Arc-cosinus of x
math.atan(x) Arc-tangent of x
math.sinh(x) Hyperbolic sine of x
math.cosh(x) Hyperbolic cosine of x
math.tanh(x) Hyperbolic tangent of x
math.asinh(x) Hyperbolic arc-sine of x
math.acosh(x) Hyperbolic arc-cosine of x
math.atanh(x) Hyperbolic arc-tangent of x
math.degree(x) Conversion of radians x to degrees
math.radians(x) Conversion of x from degrees to radians
math.factorial() Factory of x
math.gcd(x, y) Largest common divisor of x and y
math.isclose(x, y, rel_tol=1e-09, abs_tol=0.0) Compare x and y and returns if they are close to the tolerance level rel_tol ( abs_tol is the absolute minimum tolerance)
math.isfinite(x) Returns True if x is either infinite, or NaN
math.isinf(x) Returns True if x is infinite, False otherwise
math.isnan(x) Returns True if x is NaN, False if not
statistics.mean(x) Average of x
statistics.median(x) Median of x
statistics.mode(x) Mode of x
statistics.stdev(x) Standard deviation of x
statistics.variance(x) Variance of x

4.5 Some Constants

The math library offers some constants, as shown in Table 4.3.

Table 4.3: Some constants integrated in Python
Function Description
`math.pi The number Pi (\(\pi\))
math.e The constant \(e\)
math.tau The constant \(\tau\), equal to \(2\pi\)
math.inf The infinite (\(\infty\))
-math.inf Minus infinity (\(-\infty\))
math.nan Floating point number not to number

4.6 Exercise

  1. Calculate the remainder of the Euclidean division of 10 by 3.
  2. Display the largest common divisor between 6209 and 4435.
  3. Let us consider two objects: a = 18 and b = -4. Test it if:
  • a is strictly less than b,
  • a is greater than or equal to b,
  • a is different from b.
  1. Let x be the list such as x =[1, 1, 1, 2, 3, 5, 8]. Check whether:
  • 1 is in x;
  • 0 is in x;
  • 1 and 0 are in x;
  • 1 or 0 are in x;
  • 1 or 0 is not present in x.