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:
## 2
4.1.2 Subtraction
A subtraction between two numbers is performed using the -
symbol:
## 0
4.1.3 Multiplication
A multiplication between two numbers is performed using the *
symbol:
## 4
4.1.4 Division
A (real) division between two numbers is made using the symbol /
:
## 1.5
To perform a Euclidean division (or division with remainder), slash is doubled:
## 1
4.1.5 Modulo
The modulo (remainder of the Euclidean division) is obtained using the symbol %
:
## 2
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) :
## 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:
## [1, 'apple', 5, 7, 9, 11]
Same with tuples:
## (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.
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:
## False
## True
The inequality between two objects:
## False
## 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:
## False
## True
## False
## False
It is also possible to compare two strings. The comparison is carried out according to the lexicographical order:
## True
## 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:
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):
## True
As 1<9
, Python returns True
.
Let’s change x
so that the first element is greater than the first element of 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
:
## 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:
## False
4.2.3 Inclusion and exclusion
As encountered several times in Chapter 3, the inclusion tests are performed using the operator in
.
## True
To test if an item is excluded from a list, tuple, dictionary, etc., we use not in
:
## True
## False
With a dictionary:
## 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:
## True
If at least one of them is false, the logical “AND” comparison returns false:
## False
## 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 worthTrue
orNone
- the value
False
if the other object is worthFalse
.
## None
## False
## 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:
## True
If both are false, the logical “OR” comparison returns false:
## False
If one of the two objects is None
, the logical “OR” comparison returns :
True
if the other object is worthTrue
None
if the other object is worthFalse
orNone
.
## True
## None
## None
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.
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.
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
- Calculate the remainder of the Euclidean division of 10 by 3.
- Display the largest common divisor between 6209 and 4435.
- Let us consider two objects:
a = 18
andb = -4
. Test it if:
a
is strictly less thanb
,a
is greater than or equal tob
,a
is different fromb
.
- Let
x
be the list such asx =[1, 1, 1, 2, 3, 5, 8]
. Check whether:
1
is inx
;0
is inx
;1
and0
are inx
;1
or0
are inx
;1
or0
is not present inx
.