Operators are building blocks of all kind of operation we can do in any programming language. Operators are basically the symbols which operate on at least one or more operands. Operators are surrounded by literals or variables which are called operands.

Operators and operands make up expression which is evaluated to produce the result.

For Example: If you consider the expression **9 + 3 = 10** . 9, 3 and 10 are called operands. And the symbol + is called operator.

There are several types of operators in python. Which are,

- Arithmetic Operators
- Comparison Operators
- Logical Operators
- Membership Operators
- Identity Operators
- Assignment Operators
- Bitwise Operators
- Compound Assignment Operators
- Miscellaneous Operators

## Arithmetic Operators

Python arithmetic operators help to perform mathematical operation like, addition, subtraction, multiplication etc. You will find these similar across different programming languages.

+ | Addition | Adds Both Operands | x + y |

– | Subtraction | Subtracts right hand side operand from left hand side operand | x – y |

* | Multiplication | Multiplies Both operands | x * y |

/ | Division | Divides the left operand by right operand | x / y |

% | Modulo (Remainder) | Divides the left operand by right operand but returns remainder | x % y |

** | Exponent (or) Power Operator | Computes the power | a ** 2 |

// | Floor Division | It is like division operator /. But it returns the floored value of the result. For example 5/2 is 2.5 , but floor division results only 2. | x // y |

+ | Unary Positive | Change sign of number | +a +5 |

– | Unary Negative | Change sign of a number to negative | -a -8 |

## Comparison Operators

Comparison operators are also called as relational operators. These are building blocks of branching and decision making blocks of code you write. These operators return Boolean True or False based on the condition satisfied or not .

Expressions that are made up of relational operators are called as conditional expression which will be evaluated to either True or False. Conditional expressions are used in conditional code written using if, elif and else constructs .

== | Equal to operator |
This is operator compares the both left and right operands and return true if equal else flase | x == y |

!= | Not Equal to | This is opposite to equal to operator. Where this operator return if both operands are not equal | x != y |

<> | Not Equal to | This is same as not equal to != . Condition becomes true only if both operands are not equal to. This operator was removed in python 3 | x <> y |

> | Greater than | The condition becomes true if left hand operand is greater than right operand | x > y |

< | Less than | The condition becomes true only if left hand operand is less than right operand | x < y |

>= | Greater than or equal to | The condition becomes true only if left hand operand is greater than or equal to the right hand operand | x >= y |

<= | Less than or equal to | The condition becomes true only if left hand operand is less than or equal to the right hand operand | x <= y |

## Ternary Conditional Operator

This operator was introduced in Python 2.5 . Ternary Operator is used as one-liners. This operator is used in conditional assignment as well as to write if/else conditional code in one line. This is equivalent to ternary operators (? : ) supported in other languages like C/C++, Java, C# and JavaScript.

```
>>> n = 9
>>> "even number" if n % 2 == 0 else "odd number"
'odd number'
```

Notice if/else written in one line using this ternary operator

"even number" if n % 2 == 0 else "odd number"

Equivalent code of above expression written using traditional if else

```
if n % 2 == 0:
print("even number")
else:
print("odd number")
```

This syntax can effectively be used in conditional assignment as follows

```
gender = "male"
name = "neo"
greeting = f"Hello! Mr {name}" if gender.lower() == "male" else f"Hello! Ms {name}"
print(greeting)
```

Variable “greeting” was assigned conditionally based on variable gender

greeting = f"Hello! Mr {name}" if gender.lower() == "male" else f"Hello! Ms {name}"

## Logical Operators

Like any other programming languages python offers 3 logical operators. These logical operators can be applied to any literal or variable not just limited to Boolean. Like comparison operators logical operators also return either True or False. These are like conjunction words in programming languages. Logical operators help us to combine multiple conditions to write complex conditionals. These operators are not limited to use with multiple condition they can be used as short hands or Short Circuit Evaluations . If they are used in short circuiting, they return the value instead of boolean.

and | Logical AND | Condition becomes true if both operands are true | (2 > x) and (2 < y) |

or | Logical OR | Condition becomes true if at least one operand is true | (2 > x) or (2 < y) |

not | Logical NOT | It reverses the truth value of it’s operand. Returns True if operand evaluated as False, returns False if operand Evaluated as True | not x |

## Membership Operators

Membership operators in python are used to check whether an element is present in the container or not. Custom Objects can implement this operator using magic method called __contains__ . This operators can be used on container data types which includes sequence and mapping data types like string, lists and dictionaries. It doesn’t work with scalar data types int and float.

in | in | Returns True if Container or sequence contains given value | 2 in [1, 2, 3, 4, 5] |

not in | not in | Returns True if Container or Sequence doesn’t contain given value | 2 not in [4, 9 , 34] |

## Identity Operators

Identity operator compares the id(said to be address) of both operand (objects) instead of their value and return True both are same. Same id mean both objects are same not only by their value but also by the address they are referring to object in the memory.

is | Returns True if both variables refers to the same object | x is y |

is not | Returns False if both variables refers to the same object | x is not y |

## Assignment Operator

Assignment operator plays a vital role in programming. It is used to assign a value to the variable.

= | Assign value of right hand operand to the variable on the left hand | x = 2 |

:= | Assignment expression also know as the walrus operator |

### Assignment Expression

Assignment expression ask walrus operator was added to python in version 3.8 . It can also be referred as “Name Expressions” . This operator is extremely useful where it is required to name intermediate results of expression or operation. Often it is required write at least couple lines, one for capturing result of an expression into a variable and then using that variable. By using assignment expression we can put both expression and assignment of evaluated value into a variable in one line. Consider following code

Regular expression match

```
match = pattern.search(data)
if match:
....
```

Can be written as follows using :=

```
if (match := pattern.search(data)) is not None:
....
```

## Bitwise Operators

As the name says, bitwise operators work on bits. These operations are performed on integers of any number system, but operators perform operation on binary equivalent of given operands.

& | Bitwise AND | Performs Binary AND operation | x & y |

| | Bitwise OR | Performs Binary OR operation | x | y |

^ | Bitwise XOR/ Exclusive OR | Performs Binary XOR. | x ^ y |

~ | BinaryOnes Complement | Unary Operator. Flipps the bits | ~x |

<< | Binary Left Shift | Left hand operand value is changed by moving the number of bits to the left specified on right | x << 3 |

>> | Binary Right Shift | Left hand operand value is changed by moving the number of bits to the right specified on right | x >> 3 |

## Compound Assignment Operator

If you both relational and assignment operators you get compound assignment operators. Compound assignment Operators are also called **short hand** operators

+= | Add and assign | x += 1 | x = x+1 |

-= | Subtract and Assign | x -= 1 | x = x -1 |

*= | Multiply and Assign | x *= 1 | x = x * 1 |

/= | Divide and Assign | x /= 1 | x = x /1 |

%= | Modulus and Assign | x %= 2 | x = x % 2 |

**= | Exponent and Assign | x **= 2 | x = x ** 2 |

//= | Floor Divide and Assign | x //=2 | x = x // 2 |

&= | Bitwise And and Assign | x &= 2 | x = x & 2 |

|= | Bitwise OR and Assign | x |= 2 | x = x | 2 |

^= | Bitwise XOR and Assign | x ^= 2 | x = x ^ 2 |

<<= | Binary Left Shift and Assign | x <<= 2 | x = x << 2 |

>>= | Binary Right Shift and Assign | x >> =2 | x = x>>2 |

## Miscellaneous Operators

This one included all other operators we use which don’t fall under any one of above category, These operators are

. | dot | This operators is used to access attributes or methods of object | math.sqrt(3) |

() | group | These operators are used to group expression to increase it’s precedence | (x + y) * z |

[] | subscript / index | Used to access elements/ items of containers/sequences | x[1] y[‘name’] |

:: | Slice | Used on sequences to extract part of the sequence | x[::] y[2:] |

… | Ellipsis | Special value used in extending slice syntax for user defined containers | |

@ | Used to implement decorators |

## Operator Precedence

Operator precedence describes how significant operator is in the expression, thus operator precedence dictates order in which operators are evaluated in an expression. Operands of Highest precedence operator will be evaluated first followed by next precedence operator and so on. If multiple operators have same precedence in the expression order of evaluation takes place according to the operators associativity. Most of the operators have left-to-right associativity.

Following table describes these several types of operator in python sorted according to their precedence in descending order (Highest precedence to lowest precedence)

Operator | Description |

() | Parentheses. |

f(args, ..) | Function Call |

c[index], c[index:index], f(args, ..), obj.attribute | Subscription, Slicing, Function Call, Attribute Reference |

await expression | Await expression |

** | Exponentiation |

+x, -x, ~x | Positive, Negative, Bitwise NOT |

*, /, //, % | Multiplication, division, floor division, remainder |

+, – | Addition, Subtraction |

<<, >> | Bitwise left shift, Bitwise right shift |

& | Bitwise AND |

^ | Bitwise XOR |

| | Bitwise OR |

in, not in, is, is not, <, <=, >, >=, !=, == | Membership tests, identity test and comparisons |

not x | Logical NOT |

and | Logical AND |

or | Logical OR |

if-else | |

lambda | |

:= |

## Expression and Evaluation

Expressions in python are made up of any combination of literals, identifiers and operators. Expressions contains operators and operands. Where operators are what we have discussed so far and operands can be literals, variables, objects, and function calls.

Every expression will break down into a single value. Where python interpreter computes the expression to produce a single final value. This process is called evaluation.

In Python evaluation of an expression happens from left to right but when it comes to assignment, right-hand side evaluated followed by left-hand side

## Leave a Reply