We have learned about different data types, showing their value on screen and also about taking input from a user. That was all the basics of Python. From now we will gradually proceed to more programmatic concepts of Python.

This chapter is about performing operations like addition, subtraction, etc similar to what we do in Maths.

In Python, there are symbols which are used to perform certain operations on variables. These symbols are known as **operators**. For example, **(+)** is an operator which is used for adding the values of two variables.

Let's see different types of operators in Python.

- Arithmetic Operators
- Relational Operators
- Logical Operators
- Assignment Operators
- Identity Operators
- Membership Operators

## Python Arithmetic Operators

Arithmetic Operators are the type of operators which take numerical values as their operands and return a single numerical value.

Let's take two variables `a`

and `b`

having values 3 and 2 respectively.

Operator | Description | Example |
---|---|---|

+ | Adds operands | a + b = 5 |

- | Subtracts right operand from left operand | a - b = 1 |

* | Multiplies both operands | a * b = 6 |

/ | Quotient of division of left operand by right operand | a / b = 1.5 (float) |

// | Quotient of division of left operand by right | a // b = 1 (int) |

% | Remainder of division of left operand by right operand | a % b = 1 |

** | Left operand raised to the power of right operand | a ** b = 9 |

```
a = 3
b = 2
print("sum =", a + b)
print("difference =", a - b)
print("product =", a * b)
print("quotient =", a / b)
print("quotient (integer) =", a // b)
print("remainder =", a % b)
print("power =", a ** b)
```

`a, b = 3, 2`

→ Variables `a`

and `b`

are assigned values `3`

and `2`

respectively.

`print("sum =", (a + b))`

→ `sum =`

got printed as it is because it is enclosed within `" "`

. After that, the expression `(a + b)`

got evaluated and its value (3 + 2 = 5) got printed. Thus, `sum = 5`

got printed. Similarly, other statements got evaluated and printed on the screen.

We can also introduce a third variable to store the result of an operation as done in the following example.

```
a, b = 3, 2 # assigning values to variables a and b
c = a + b # storing sum of a and b in c
print("sum =", c)
```

### Difference Between / and // Operators in Python

Both `/`

and `//`

operators divide the operands and return the quotient. The difference is that / returns the quotient as it is while // returns the quotient by truncating its fractional part and returning only the integer part.

```
a, b = 5, 3 # assigning values to variables a and b
print("quotient =", a / b)
print("quotient (integer) =", a // b)
```

Another difference between the two operators is that `/`

always return a float (even if the operand is perfectly divisible) and `//`

always return an integer.

```
a, b = 4, 2 # assigning values to variables a and b
print("quotient =", (a / b), "of type", type(a / b))
print("quotient (integer) =", (a // b), "of type", type(a // b))
```

As you can see, `/`

returned the quotient as `2.0`

which is of type `float`

, whereas `//`

returned the quotient as `2`

which is of type `int`

.

## Python Relational Operators

Relational Operators check the relationship between two operands. They return `True`

if the relationship is true and `False`

if it is false.

Following is the list of relational operators in Python.

Again, take two variables `a`

and `b`

having values 3 and 2 respectively.

Operator | Description | Example |
---|---|---|

== | Equal to | (a == b) is False |

!= | Not equal to | (a != b) is True |

> | Greater than | (a > b) is True |

< | Less than | (a < b) is False |

>= | Greater than or equal to | (a >= b) is True |

<= | Less than or equal to | (a <= b) is False |

** ==** → It is used to check if two values are equal or not. It returns True if the values are equal, otherwise it returns False.

```
print(2==2)
print(2==3)
```

** !=** → It is just the opposite of ==. It is True if both values are not equal and False if they are equal.

```
print(2!=2)
print(2!=3)
```

** >** → Similar to > of mathematics. It is used to check if one value is greater than another or not.

```
print(2>3)
print(2<3)
```

(greater than or equal to) → It is similar to > but will be True even if the values are equal. It is similar to >= of Maths.**>=**

```
print(2>=3)
print(2>=2)
```

```
a = 3
b = 2
print("(a == b) :", a == b)
print("(a != b) :", a != b)
print("(a > b) :", a > b)
print("(a < b) :", a < b)
print("(a >= b) :", a >= b)
print("(a <= b) :", a <= b)
```

In the above example, since the value of `a`

is not equal to that of `b`

, therefore `(a == b)`

(equal to) returned `False`

and `(a !=b)`

(not equal to) returned `True`

.

Since the value of `a`

is greater than that of `b`

, therefore (`a > b`

) (greater than) and `(a >= b)`

(greater than or equal to) returned `True`

whereas `(a < b)`

(less than) and `(a <= b)`

(less than or equal to) returned `False`

.

### Difference Between = And == in Python

Although = and == seem to be the same, they are quite different from each other. = is the **assignment operator** while **==** is the **equality operator**.

= assigns values from its right side operands to its left side operands whereas == compares values.

```
x = 10
print(x == 10)
```

By writing `x = 10`

, we assigned a value *10* to `x`

, whereas by writing `x == 10`

, we checked if the value of `x`

is equal to *10* or not.

```
name = "Sam"
print(name == "Sam")
print(name == "Aam")
```

`=`

assigns a value "`Sam`

" to the variable `name`

and `==`

checks whether the value of the variable `name`

is "`Sam`

" or not.

## Python Logical Operators

Look at the following table in which Exp1 and Exp2 are the two operands.

Exp1 | Operator | Exp1 | Output (Boolean) |
---|---|---|---|

True | and | True | True |

True | and | False | False |

False | and | False | False |

True | or | True | True |

True | or | false | True |

False | or | False | False |

So, if we use `and`

as an operator with any two operands and if both of them are `True`

, then the result is `True`

. Otherwise, the result is `False`

.

If we use `or`

as an operator and if any of the two operands is `True`

, then the result is `True`

, and if both the operands are `False`

then the result is False.

`and`

can be understood as both (both first and second)

`or`

can be understood as either (either first or second or both).

`and`

and `or`

of programming are very much similar to English words 'and' and 'or'.

In English,

A and B - Both A and B.

A or B - Either A or B.

In programming also,

A and B - Both A and B.

A or B - Either A or B or both.

Again assume the value of `a`

to be True and that of `b`

to be False.

Operator | Description | Example |
---|---|---|

and | If both the operands are True, then the condition becomes True | (a and b) is False |

or | If any one or both the operands are True, then the condition becomes True | (a or b) is True |

not | It is used to reverse the condition. So, if a condition is True, not makes it False and vice versa. | not(a) is False, not(b) is True |

```
x = 10
y = 20
print(x == 10 and y == 20)
print(x == 3 or y == 20)
```

Here, `x`

is 10 and `y`

is 20. So, `x == 10`

is True and `y == 20`

is also `True`

. Therefore, `x == 10 and y == 20`

is also `True`

because both the operands are True (`and`

is used as the operator).

In the next statement, `x == 3`

is False but `y == 20`

is `True`

. Therefore, `x == 3 or y == 20`

is `True`

because at least one operand is `True`

(`or`

is used as the operator).

```
x = 10
y = 20
print(not(x == 10 and y == 20))
print(not(x == 3 or y == 20))
```

`not`

operator converts `True`

to `False`

and vice versa.

This is the same example as the previous one. We just used not here and saw the answers get reversed.

## Python Assignment Operators

Assignment Operators are used to assign values from its **right side operands to its left side operands**. The most common assignment operator is

.**=**

If we write `a = 10`

, it means that we are assigning a value 10 to the variable `a`

.

*10 = a*would give us an error because we are trying to assign the variable a (right side) to 10 (left side) and this is invalid as 10 is a constant and we can't change its value to something else, a in this case.

There are more assignment operators which are listed in the following table.

Operator | Description | Example |
---|---|---|

= | Assigns value of right operand to left operand | C = A + B |

+= | Adds the value of right operand to left operand and assigns the final value to the left operand | C += A is same as C = C + A |

-= | Subtracts the value of right operand from left operand and assigns the final value to left operand | C -= A is same as C = C - A |

*= | Multiplies the value of right operand to left operand and assigns the final value to left operand | C *= A is same as C = C * A |

/= | Divides the value of left operand by right operand and assigns the quotient to left operand | C /= A is same as C = C / A |

//= | Divides the value of left operand by right operand and assigns the quotient (integer) to left operand | C //= A is same as C = C // A |

%= | Takes modulus using two operands and assigns the result to left operand | C %= A is same as C = C % A |

**= | Calculates left operand raised to the power right operand and assigns the result to the left operand | C **= A is same as C = C ** A |

To understand their use, consider the value of a variable `n`

as 5. Now if we write `n += 2`

, the expression gets evaluated as **n = n + 2** thus making the value of `n`

as 7 ( n = 5 + 2 ).

We said that n+=2 is evaluated to n = n+2 but n = n+2 is evaluated? This is little different to what happens in normal mathematics. Here, the value of n + 2 is calculated first (using the old value of n).

So, n+2 is calculated first and thus it will become 5+2 i.e., 7.

Thus the expression will become n = 5+2 or n=7.

So the calculated value is assigned to n, changing the value of *n* (making* n = 7*).

The decision of evaluating n+2 first is not a random one. Python has preset rules of which operation it is going to perform first which you will learn later in this chapter.

Let's look at an example.

```
a = 7
a += 4 # equivalent to a = a + 4
print("Value of a after a += 4:", a)
a -= 4 # equivalent to a = a - 4
print("Value of a after a -= 4:", a)
```

In the above example, initially, the value of `a`

is 7.

The expression `a += 4`

got evaluated as *a = a + 4* thus making the value of `a`

as 11. After this, the expression `a -= 4`

got evaluated as *a = a - 4* thus subtracting 4 from the current value of `a`

(i.e. 11) and making it 7 again.

## Python Identity Operator

These are used to check if two operands (values) are located in the same memory. There are two identity operators in Python - `is`

and `is not`

.

Operator | Description |
---|---|

is | Returns True if the operands refer to the same object. Otherwise returns False. |

is not | Returns True if the operands do not refer to the same object. Otherwise returns False. |

In the chapter Variables, we saw that everything in Python is stored in a different memory location. `is`

operator is used to check if the operands belong to the same memory location.

Also note that two variables having the same value does not necessarily mean that their values are stored in the same memory location.

Look at the following example.

```
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)
```

The variables `a`

and `b`

store two separate lists having the same value. Since these are two separate lists, these are stored in different memory locations. `a == b`

returned `True`

because the `==`

operator compares the values of the operands and both the lists have the same value. `a is b`

returned `False`

because the is operator compares the memory location of the operands and both the lists are stored in different memory locations.

Now consider another example.

```
a = [1, 2, 3]
b = a
print(a == b)
print(a is b)
print(a is not b)
```

The variable `a`

is assigned a list which is stored in some memory location. Therefore, `a`

points to the memory location of this list. On writing `b = a`

, `b`

also started pointing to the memory location which a is pointing to. Since both `a`

and `b`

are pointing to the same memory location where the list is stored, `a is b`

returned `True`

and `a is not b`

returned `False`

.

## Python Membership Operators

These are used to check if a value is present in a sequence like string, list, tuple, etc. There are two membership operators `in`

Python - in and `not in`

.

Operator | Description |
---|---|

in | Returns True if the value is present in the sequence. Otherwise returns False. |

not in | Returns True if the value is not present in the sequence. Otherwise returns False. |

```
a = "Python programming"
print('on' in a)
print('p' not in a)
b = ['Hello', 1, 2, 3]
print(2 in b)
```

`'on' in a`

→ Returned `True`

because ‘on’ is present in "Python programming".

`'p' not in a`

→ Returned `False`

because ‘p’ is present in "Python programming".

`2 in b`

→ Returned `True`

because 2 is present in ['Hello', 1, 2, 3].

We can also test for a dictionary with membership operators, but the search happens only for the key, not for the value.

```
a = {1: 'Blue', 2: 'Green', 'default': 'Orange'}
print(2 in a)
print('Blue' in a)
```

`a`

is a dictionary having 1, 2 and ‘default’ as keys and ‘Blue’, ‘Green’ and ‘Orange’ as the corresponding values.

`2 in a`

→ Returned `True`

because 2 is a key present in the dictionary `a`

.

`'Blue' in a`

→ Returned `False`

because 'Blue' is not a key present in the dictionary `a`

. Remember that we search for just the keys, not the values.

We will be looking at more examples of Identity and Membership operators in later chapters.

## Precedence of Operators in Python

In Maths, you might have learned about the BODMAS rule, but that rule is not applied here. If we have written more than one operator in an expression, then the operation that should be done first is governed by the following rule :- **Expression inside brackets '()' are evaluated first**. After that, the following table is followed (The operator at the top has the highest precedence (priority) and that at the bottom has the least precedence (priority)):

Operator | Associativity |
---|---|

** | Right to left |

* / // % | Left to right |

+ = | left to right |

== != > < >= <= is is not in not in | Left to right |

not | Right to left |

and | Left to right |

or | Left to right |

= += -= *= /= //= %= | Right to left |

Let's consider an expression

**n = 4 * 8 + 7**

Since the priority order of the multiplication operator ( * ) is greater than that of the addition operator ( + ), so first 4 will get multiplied with 8 and after that 7 will be added to the product.

Suppose two operators have the same priority order in an expression, then the evaluation will start from left or right (if associativity is left to right) and from right to left (if associativity is from right to left) as shown in the above table.

For example, take the expression.

**10 / 5 - 2 * 3 + 8**

Since the priorities of / and * are greater than those of + and -, therefore / and * will be evaluated first. Since / and * have the same priority order, so these will be evaluated from left to right simplifying to the following expression. (In the expression, / is written at left and * at right)

**2 - 2 * 3 + 8**

After /, * will be evaluated resulting in the following expression

**2 - 6 + 8**

Again - and + have the same precedence, therefore these will also be evaluated from left to right i.e. first 6 will be subtracted from 2 after which 8 will be added resulting in 4.

Hence we will get the result as 4.

Remember the expression n = n + 2 used earlier in this chapter? Now you can understand that because the + operator has higher precedence than the = operator, the value n + 2 is calculated first making the expression n = 7. Also, the = operator has associativity from right to left, and thus the value on the right side of the = operator is assigned to the variable on the left side i.e., 7 is assigned to n, making the value of n equal to 7.