Python 3 Operators: Arithmetic, Comparison, Logical and More - Techno informations
Coding

Python 3 Operators: Arithmetic, Comparison, Logical and More

What Are Operators in Python?

Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.

For example:

>>> a = 10
>>> b = 20
>>> a + b
30

In this case, the + operator adds the operands a and b together. An operand can be either a literal value or a variable that references an object:

>>> a = 10
>>> b = 20
>>> a + b - 5
25

A sequence of operands and operators, like a + b - 5, is called an expression. Python supports many operators for combining data objects into expressions.

Types of Operator

Python language supports the following types of operators:

  • Arithmetic Operators
  • Comparison (Relational) Operators
  • Assignment Operators
  • Logical Operators
  • Bitwise Operators
  • Membership Operators
  • Identity Operators

Let us have a look at all the operators one by one.

Arithmetic Operators

Assume variable a holds the value 10 and variable b holds the value 21, then

OperatorDescriptionExample
+ AdditionAdds values on either side of the operator.a + b = 31
- SubtractionSubtracts right hand operand from left hand operand.a – b = -11
* MultiplicationMultiplies values on either side of the operatora * b = 210
/ DivisionDivides left hand operand by right hand operandb / a = 2.1
% ModulusDivides left hand operand by right hand operand and returns remainderb % a = 1
** ExponentPerforms exponential (power) calculation on operatorsa**b =10 to the power 20
//Floor Division – The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0

Here are some examples of these operators in use:

>>> a = 4
>>> b = 3
>>> +a
4
>>> -b
-3
>>> a + b
7
>>> a - b
1
>>> a * b
12
>>> a / b
1.3333333333333333
>>> a % b
1
>>> a ** b
64

The result of standard division (/) is always a float, even if the dividend is evenly divisible by the divisor:

>>> 10 / 5
2.0
>>> type(10 / 5)
<class 'float'>

When the result of floor division (//) is positive, it is as though the fractional portion is truncated off, leaving only the integer portion. When the result is negative, the result is rounded down to the next smallest (greater negative) integer:

>>> 10 / 4
2.5
>>> 10 // 4
2
>>> 10 // -4
-3
>>> -10 // 4
-3
>>> -10 // -4
2

Note, by the way, that in a REPL session, you can display the value of an expression by just typing it in at the >>> prompt without print(), the same as you can with a literal value or variable:

>>> 25
25
>>> x = 4
>>> y = 6
>>> x
4
>>> y
6
>>> x * 25 + y
106

Comparison Operators

These operators compare the values on either side of them and decide the relation among them. They are also called Relational operators.

Assume variable a holds the value 10 and variable b holds the value 20, then

OperatorDescriptionExample
==If the values of two operands are equal, then the condition becomes true.(a == b) is not true.
!=If values of two operands are not equal, then condition becomes true.(a!= b) is true.
>If the value of left operand is greater than the value of right operand, then condition becomes true.(a > b) is not true.
<If the value of left operand is less than the value of right operand, then condition becomes true.(a < b) is true.
>=If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.(a >= b) is not true.
<=If the value of left operand is less than or equal to the value of right operand, then condition becomes true.(a <= b) is true.

Here are examples of the comparison operators in use:

>>> a = 10
>>> b = 20
>>> a == b
False
>>> a != b
True
>>> a <= b
True
>>> a >= b
False

>>> a = 30
>>> b = 30
>>> a == b
True
>>> a <= b
True
>>> a >= b
True

Assignment Operators

Theassignment operators in Python are used to store data into a variable. We’ve already used the most common assingment operator (=), but there are many more of them.

Assume variable a holds the value 10 and variable b holds the value 20, then

OperatorDescriptionExample
=Assigns values from right side operands to left side operandc = a + b assigns value of a + b into c
+= Add ANDIt adds right operand to the left operand and assign the result to left operandc += a is equivalent to c = c + a
-= Subtract ANDIt subtracts right operand from the left operand and assign the result to left operandc -= a is equivalent to c = c – a
*= Multiply ANDIt multiplies right operand with the left operand and assign the result to left operandc *= a is equivalent to c = c * a
/= Divide ANDIt divides left operand with the right operand and assign the result to left operandc /= a is equivalent to c = c / ac /= a is equivalent to c = c / a
%= Modulus ANDIt takes modulus using two operands and assign the result to left operandc %= a is equivalent to c = c % a
**= Exponent ANDPerforms exponential (power) calculation on operators and assign value to the left operandc **= a is equivalent to c = c ** a
//= Floor DivisionIt performs floor division on operators and assign value to the left operandc //= a is equivalent to c = c // a

Bitwise Operators

Bitwise operators treat operands as sequences of binary digits and operate on them bit by bit. The following operators are supported:

OperatorExampleMeaningResult
&a & bbitwise ANDEach bit position in the result is the logical AND of the bits in the corresponding position of the operands. (1 if both are 1, otherwise 0.)
|a | bbitwise OREach bit position in the result is the logical OR of the bits in the corresponding position of the operands. (1 if either is 1, otherwise 0.)
~~abitwise negationEach bit position in the result is the logical negation of the bit in the corresponding position of the operand. (1 if 00 if 1.)
^a ^ bbitwise XOR (exclusive OR)Each bit position in the result is the logical XOR of the bits in the corresponding position of the operands. (1 if the bits in the operands are different, 0 if they are the same.)
>>a >> nShift right nplacesEach bit is shifted right n places.
<<a << nShift left nplacesEach bit is shifted left n places.

Here are some examples:

>>> '0b{:04b}'.format(0b1100 & 0b1010)
'0b1000'
>>> '0b{:04b}'.format(0b1100 | 0b1010)
'0b1110'
>>> '0b{:04b}'.format(0b1100 ^ 0b1010)
'0b0110'
>>> '0b{:04b}'.format(0b1100 >> 2)
'0b0011'
>>> '0b{:04b}'.format(0b0011 << 2)
'0b1100'

Note: The purpose of the '0b{:04b}'.format() is to format the numeric output of the bitwise operations, to make them easier to read. You will see the format() method in much more detail later. For now, just pay attention to the operands of the bitwise operations, and the results.

Logical Operators

There are three logical operators that are used to compare values. They evaluate expressions down to Boolean values, returning either True or False. These operators are andor, and not and are defined in the table below.

OperatorWhat it meansWhat it looks like
andTrue if both are truex and y
orTrue if at least one is truex or y
notTrue only if falsenot x

To understand how logical operators work, let’s evaluate three expressions:

print((9 > 7) and (2 < 4))  # Both original expressions are True
print((8 == 8) or (6 != 6)) # One original expression is True
print(not(3 <= 1))          # The original expression is False

The result will be as follows:

True
True
True

Identity Operators

Python provides two operators, is and is not, that determine whether the given operands have the same identity—that is, refer to the same object. This is not the same thing as equality, which means the two operands refer to objects that contain the same data but are not necessarily the same object.

OperatorDescriptionExample
isEvaluates to true if the variables on either side of the operator point to the same object and false otherwise.x is y, here is results in 1 if id(x) equals id(y).
is notEvaluates to false if the variables on either side of the operator point to the same object and true otherwise.x is not y, here is notresults in 1 if id(x) is not equal to id(y).

Here is an example of two object that are equal but not identical:

>>> x = 1001
>>> y = 1000 + 1
>>> print(x, y)
1001 1001

>>> x == y
True
>>> x is y
False

Here, x and y both refer to objects whose value is 1001. They are equal. But they do not reference the same object, as you can verify:

>>> id(x)
60307920
>>> id(y)
60307936

x and y do not have the same identity, and x is y returns False.

You saw previously that when you make an assignment like x = y, Python merely creates a second reference to the same object, and that you could confirm that fact with the id()function. You can also confirm it using the is operator:

>>> a = 'I am a string'
>>> b = a
>>> id(a)
55993992
>>> id(b)
55993992

>>> a is b
True
>>> a == b
True

In this case, since a and b reference the same object, it stands to reason that a and b would be equal as well.

Unsurprisingly, the opposite of is is is not:

>>> x = 10
>>> y = 20
>>> x is not y
True

Membership Operators

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below

OperatorDescriptionExample
inEvaluates to true if it finds a variable in the specified sequence and false otherwise.x in y, here in results in a 1 if x is a member of sequence y.
not inEvaluates to true if it does not finds a variable in the specified sequence and false otherwise.x not in y, here not in results in a 1 if x is not a member of sequence y.

Operators Precedence

The following table lists all operators from highest precedence to the lowest.

OperatorDescription
()Parentheses (grouping)
f(args…)Function call
x[index:index]Slicing
x[index]Subscription
x.attributeAttribute reference
**Exponentiation
~xBitwise not
+x, –xPositive, negative
*, /, %Multiplication, division, remainder
+, –Addition, subtraction
<<, >>Bitwise shifts
&Bitwise AND
^Bitwise XOR
|Bitwise OR
in, not in, is, is not, <, <=, >, >=,
<>, !=, ==
Comparisons, membership, identity
not xBoolean NOT
andBoolean AND
orBoolean OR
lambdaLambda expression

Highest precedence at top, lowest at bottom.

Operators in the same box evaluate left to right.

Conclusion

In this tutorial, you learned about the diverse operators Python supports to combine objects into expressions.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also
Close
Back to top button