Operators#
Here is considered different python operators and way to operate with them.
Order#
In an expression, certain operators have precedence over others. This means that operations with higher precedence will be executed before those with lower precedence. Find out more in the specific page.
For example, the operator *
has higher precedence than the operator +
. Therefore, in the expression 3 + 4 * 2
, the operations will be performed in the following order: first, 4 * 2
is evaluated to 8
, and then 3 + 8
results in 11
. This is done instead of performing 3 + 4
first to get 7
, and then multiplying 7 * 2
to get 14
.
3+4*2
11
Associativity is a property of operators that determines the order in which operations of the same precedence are performed. It specifies whether the operations are executed from left to right or from right to left.
For example, the **
operator has right-to-left associativity. This means that it is evaluated from right to left. Consider the following example:
2**3**2
512
The result is \(2^{3^2} = 2^9=512\) but not \((2^3)^2 = 8^2=64\). The result is equivalent to the 2**(3**2)
but not to the (2**3)**2
.
The expression 2 / 0.5 / 2
demonstrates left-to-right associativity. The following example shows the result.
2/0.5/2
2.0
The result is \(\frac{2/0.5}{2}=\frac{4}{2}=2\) but not \(\frac{2}{0.5/2}=\frac{2}{1/4}=8\). The result is equivalent to the (2/0.5)/2
but no to the 2/(0.5/2)
.
/
- division operator#
It always returns the data type float
, even if the result can be interpreted as int
.
type(4/2)
float
//
- integer division#
This operator simply divides the operands and returns the result without the floating point part.
5//2
2
Unlike regular division, it always returns int
data type.
print(type(6/2))
print(type(6//2))
int
Note that the rounding is always on the lower side. So if we apply this operator to the negative number, we get the lower number that is the result of the even division.
-5//2
-3