# Python Operators Explained in Detail with Examples

## Introduction to Python Operators

Every programming language has operators which are used to perform various operations on different types of operations on given operants. In Python, there are seven operators namely,

Arithmetic operators, logic operators, comparison operators, assignment operators, bitwise operators, and we also have two special kinds of operators as well ( identity operator and membership operator). In this tutorial, we will cover each of these operators along with different examples.  We will also learn about operators' precedence of these operators in Python as well.

## Arithmetic operators in Python

As the name suggests, these operators perform various arithmetic operations and calculations like addition, multiplications, division, etc. See the following tables which show some of the basic and most popular arithmetic operators used in Python.

• ` +` operator:  used to add two numbers.
• `-` operator: used for subtraction.
• ` *`  operator: used for multiplication.
• ` /` operator: give out quotient when two numbers are divided. The result always has type float.
• ` **` operator: used to find the power of the number
• ` %` operator: used to find the remainder when two numbers are divided.
• ` //` operator: used to find quotient when two numbers are divided and rounded to the next smallest whole number

See the following example which uses different arithmetic operators.

``````# adding number
print(2+3) # 5 out put

# subtracting number
print(4-3) # 1 output

# multiply number
print(2*3) # 6 output

# dividing numbers
print(3/2) # 1.5 output

# modulus finding
print(10%2) # 0 output``````

Output:

```5
1
6
1.5
0 ```

In python by default, the output of division is always the float number. If we want an integer output, then we have to explicitly convert float to integer.

See the example below.

``````# dividing type
print(type(4/3))``````

Output:

`<class 'float'>`

## Comparison operators in Python

Comparison operators are also known as rational operators as well. They are used to compare different values.  They evaluate different types of expressions and manipulate the values of variables by performing different operations on them. Here is a table of common comparison operators used in python.

• `==` operator:  return true if the value of a is equal to the value of b, otherwise false.
• `!=` operator: return True if a is not equal to b and False otherwise.
• `<` operator: used to compare two numbers( less than operator)
• ` >` operator: used to compare two numbers( greater than operator)
• `>=` operator: used to compare two numbers ( greater than or equal to operator)
• ` <=` operator: used to compare two numbers ( less than or equal to operator)

The comparison operators return true or false depending on the condition. See the following examples.

``````# comparing two numbers
print(10==9)  #false

# using inequality
print(10!=9)  #true

# using greater operator
print(10>9)  #true

# using greater or equal operator
print(10>=9)  #true

# using less then operator
print(10<9)  #false

# using less than or equal operator
print(10<=9)  #false``````

Output:

```False
True
True
True
False
False```

As you can see the output is either true or false so the comparison operators are usually used in boolean context.

## Logical operators in Python

Python logical operators are used to evaluate the one or more than one condition between variables or operands by providing specific results. i.e `True` and `False`

Here is a table showing some of python's logical operators and their uses.

• `and` : True if both sides of the operand is True
• `or` : True if either of the operand is True
• `not` : Complements the operand

### AND operator in Python

AND operator in python takes at least two operands and returns `True` if and only if all the operands/ conditions are `True` else it will return `False`. We will take different conditions and examples to see how we can use AND operator in various situations.

``````# return false if both are false
print(False and False)

# return true if all conditions are true
print(True and True)

# return false if any one is false
print(False and True)``````

Output:

```False
True
False```

We can use AND operators on multiple operands or variables at the same time. See the example below:

``````# return false if atleast one is false
print(False and False and True)

# return true if all conditions are true
print(True and True and True and True)``````

Output:

```False
True```

Now let us take a more practical example and see how we can use AND operators with different conditions.

``````# defining variables
x = 5
y = 10
z = 20

# checks conditions using AND
if (x >y and y > z):
print("{} is largest".format(x))

# check conditions using AND
elif (y > x and x > z):
print("{} is largest".format(y))

# Check condition using AND
elif (z> x and x> y):
print("{} is the largest".format(z))``````

Output:

`5 is largest`

### OR operator in Python

OR operator in Python takes at least two operants or conditions and returns True if any of the condition/operands is true and returns False if all the operands are considered to be false.

``````# both condition are true
print(True or True)

# one conditions is false
print(True or False)

# both condition are false
print(False or False)``````

Output:

```True
True
False```

In a similar way, Or operator can be used with multiple operands or conditions and return true if any of the given operands is true.  See the example below:

``````# return true if any of the conditions is true
print(False or False or False or True)

# return false if all conditions are false
print(False or False or False or False)``````

Output:

```True
False```

Now let us take a more practical example and see how we can use OR operators in different situations.

``````# defining variables
x = 3
y = 10

# use or statement inside if
if (x%5 or x%10):
print("{} is not divisible by either 5 or 10".format(x))

# use or operator inside if statement
if (y%5==0 or y%10==0):
print("{} is divisible by either 5 or 10".format(y))``````

Output:

```3 is not divisible by either 5 or 10
10 is divisible by either 5 or 10```

### NOT operator in Python

The not logical operator is used with a single boolean value. It returns false if the boolean is true and vice versa. It actually reverses the boolean value. See the example below:

``````# using not operator on true
print(not(True))

# using not operator on false
print(not(False))``````

Output:

```False
True```

In Python 0 is considered to be False and any other numeric value other than zero is treated as True. See the example below on how not operator converts True value to false value.

``````# using not operator on true
print(not 5)

# using not operator on false
print(not 0)``````

Output:

```False
True```

Now let us take a practical example and see how we can use not operator in practical problems.

``````# defining variable
x = 5

# using not with if statement
if not x:
print("Boolean value of x is True")

# if the condition is false:
# not will make it true
if not (x%3 == 0 or x%5 == 0):
print("5 is not divisible by either 3 or 5")
else:
print("5 is divisible by either 3 or 5")``````

Output:

`5 is divisible by either 3 or 5`

### Chained comparison using logical operators

We can use an arbitrary length comparison operator in a comparison. See the example below of how we can use logical operators in chained comparison.

``````# using chained comparison
print(3>5 >=6)``````

Output:

`False`

Let us now use the logical operator in the same example.

``````# using logical operator in  chained comparison
print(3>5 and 5 >=6)``````

Output:

`False`

## Bitwise comparison operators in Python

Bitwise operators in Python are used to operate at a binary level. This means they look directly at the binary digits or binary bits of an integer. The different types of bitwise operators are Bitwise OR, bitwise and, bitwise not, XOR, right shift, and left shift. In this section, we will cover all these different types of operators.

See the table below which describes the symbol and the description of each of these operators.

• `&` operator: Each 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.)
• `|` operator: Each 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.)
• `~` operator: Each bit position in the result is the logical negation of the bit in the corresponding position of the operand. (1 if 0, 0 if 1.)
• `^` operator: 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.)
• `>>` operator: Each bit is shifted right n places
• `>>` operator: Each bit is shifted left n places

### Bitwise AND and OR operator

Bitwise AND operator is similar to logical AND operator. It returns 1 if both are True, else returns 0.

``````# using bitwise and operators
print(3>5 & 5 >=6)``````

Output:

`False`

Similarly bitwise or operator returns 1 or True if any of the operands is 1/True else it returns false.

See the example below:

``````# using bitwise Or operators
print(3<5 | 5 < 6)``````

Output:

`True`

### Bitwise negation in Python

A bitwise negation performs logical negation on a given number by flipping all of its bits. See the below diagram which explains the negation clearly.

The inverted bits are a complement to one, which turns zeros into ones and ones into zeros

Bitwise negation seems to be straightforward but we have to take extreme caution when using them in Python. Because everything we read so far is based on the assumption that numbers are represented with unsigned integers.

But in Python, all the numbers have implicit signs attached to them. This shows up when we do bitwise negation on any number.

See the example below:

``````# bitwise negation
print(~(200))``````

Output:

`-201`

The output might be confusing for you. If we convert `200` to binary then we get `11001000` and by applying bitwise negation on the binary, it should be `110111` which is equal to `55` but unexpectedly we get `-201`. To deal with this problem and get desired output, we can add the following code to our bitwise negation.

``````# bitwise negation
print(~(200) & 255)``````

Output:

`55`

### Bitwise XOR operator in Python

XOR operator takes different inputs and returns 1 if any of the input has one ( not boht) , else returns 0.

See example below.

You can see that the XOR operator had returned 1 if any of the bits was 1 and return 0 if both inputs were 0 or 1 at the same time. Now let us take the same example and try to implement it in Python. 1101 is equal to 13 and 101 is equal to 5. See example below

``````# bitwise negation

print(13 ^ 5)``````

Output:

``8 ``

8 in binary is equal to 1000.

### Left and right shifts in Python

The left shift operator moves the bits of its first operand to the left place by the number of places specified in its second operand. It also takes care of inserting enough zero bits to fill the gap that arises on the right edge of the new bet pattern.

Let us take an example to see how the left shift actually works.

``````# using left shift operator
print((8 << 3) & 255)``````

Output:

`64`

Now let us try to understand how we get 64. So, when we convert 8 to binary we get 1000 and when we apply a left shift of 3 bits on 1000 we get 1000000  which is equal to 8 in an integer value.

The right shift operator is opposite to the left shift one and instead of moving bits to the left, it pushes them to the right by the specified number of places. The rightmost bits always get dropped.

See the example below to understand the right shift in more detail.

``````# using right shift operator

print((8 >> 3) & 255)``````

Output:

`1`

Now let us try to figure out why we get one.

As we know 1000 is the binary form of 8. So, when we apply the right shift by 3 digits, then 3 bits in the binary number from the right side are going to be dropped and we left with only 1.

## Special operators in Python

So far we have covered all the operators which are very commonly used in Python. However, there are two more Python operators which are considered to be special operators. Identity operator and membership operator. In this section, we will cover the two special operators of Python.

### Identity operators in Python

Identity operator contains two different operators, is and is not, which determines whether the given operands have the same identity or not. It is different from equality which means the two operands refer to objects that contain the same data but are not necessarily the same object.

Let us take an example and see the difference.

``````# defining variables, both have value of 10
x = []
y = []

# using equality
print(x == y)  # True

# using identity operator
print(x is y)  # False``````

Output:

```True
False```

It is because the keyword takes the IDs and checks if they are equal. See the output which gives different ID values.

``````# defining variables, both have value of 10
x = []
y = []

# using equality
print(x == y)  # True
print(id(x))

# using identity operator
print(x is y)  # False
print(id(y))``````

Output:

```True
2901521355208
False
2901521355720```

`is` operator returns false because both objects have different IDs.

Now `is not` operator is opposite of `is`. See the example below:

``````# defining variables, both have value of 10
x = []
y = []

# using is not identity operator
print(x is not y)  # True``````

Output:

`True`

### Membership operators in Python

Membership operator contains two different operators, is and is not. It is used to verify whether a particular element is a part of a sequence or not. A sequence can be a list, string, sets , tuple and dictionary.

See the example below to understand the use of membership operators.

``````# defining set
x =["a", "b", "c", "d"]

print("z" in x) #false
print("a" in x) # True
print("a" not in x) # False``````

Output:

```False
True
False```

In a similar way we can use membership operators on different sequences as well.

``````# defining tuple
x =(1, 2, 3, 4, 5)

print(1 in x) #True
print(6 in x) # False
print(100 not in x) # True``````

Output:

```True
False
True```

## Augmented operators in Python

Unlike normal assignment operators, Augmented Assignment Operators are used to replace those statements where a binary operator takes two operands, variable1 and variable1 and then assigns a final result back to one of the operands.  The following are the augmented assignment operators:

``+=  -=  *=  /=  %=  **=  <<=  >>=  &=  ^=  |=``

Now let us take some examples to see how we can use these assignments in python code.

``````x = 100
y = 100

x = x + 100

# using augmented operator
y +=100
print(x)
print(y)``````

Output:

``````200
200``````

## Operators precedence in Python

All operators that the language supports are assigned precedence. In an expression, all operators of highest precedence are performed first. Once those results are obtained, operators of the next highest precedence are performed. So it continues until the expression is fully evaluated. Any operators of equal precedence are performed in left-to-right order.

The following table shows the precedence of operators in Python.

Now let us take a simple example and see the result.

``print(2 +  5*5)``

Output:

`27`

The multiplication is performed first and then added according to the precedence rule.

Now let take the example of the operators which have the same precedence and see how it works in python

``````print(2 + 5 - 10)
print(5 - 5 + 2)``````

Output:

```-3
2```

You can see that we get different outputs when we change the places of operators. It is because in python when we use the same different operators with the same precedence, python will read them from left to right.

## Summary

Python has seven different types of operators. Arithmetic operators, logic operators, assignment operators, augmented operators, bitwise operators, and two special kinds of operators; membership operator and identity operator. In this tutorial, we learned about each type of these operators by taking different examples.  Moreover, we also covered the precedence of these operators over each other.

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation. For any other feedbacks or questions you can either use the comments section or contact me form. 