Python 4.1 - Operators

We all know some basic mathematics like addition, subtraction, multiplication and division. These all are operations which are also performed on data in a program. A program requires data to perform operations like addition, subtraction etc. And we know that data is stored into variables. So we can perform operations on those data or variables. So how do we perform operations on data? Operations are performed on data by using operators. For example, in statement ‘x + y’, we are performing an addition operation on variables ‘x’ and ‘y’. Here symbol ‘+’ is called an operator which is used to perform an addition operation. And ‘x’ and ‘y’ are called variables or operands. So operators are symbols (such as +, -, *, % etc.) which are used to perform operations on operands. 

z = x + y – x

Here z, x and y are operands or variables and ‘+’, ‘-’ and ‘=’ are operators.

There are many types of operators available in Python which are used to perform different types of operations on data. We can classify operators in two categories – Unary operators and Binary operators.

Types of operators  

So there are two types of operators in Python –

·         Unary operators

·         Binary operators

1.   Unary operators

The unary operator is the operator who operates or works on only one operand. Unary means one. There are two types of unary operators –

·         Unary minus ( - )

·         Unary plus ( + )

These operators can only be used with single operand. ‘Unary plus (+)’ and ‘unary minus (-)’ operators represent the positive and negative signs of a value. For example, when we want to store a positive number into a variable then we simply write, x = 5 or x = +5 where ‘+’ symbol before 5 is a ‘unary +’ operator and represents that 5 is a positive number. It is not mandatory to write ‘unary +’ before an operand. So when we store a positive number, we do not need to write ‘+’ symbol before operand.

But when we want to store a negative number then we have to use unary minus (-) operator before operand. For example, x = - 5 where the symbol ‘-’ represents the unary minus operator and tells that it is a negative number. We can also write ‘x = -y’ where ‘unary -’ is used with only one operand ‘y’. Then we stored the result into ‘x’.

As you can see, unary operator allowed only one operand, ‘5’ and ‘y’ in our case. Do not get confused the unary ‘+’ operator with addition (+) operator. We have not used ‘+’ or ‘-’ operator with two operands. We just used ‘+’ and ‘-’ with single operand. For example, if I write ‘x = 5 + 15’ or ‘x = y + z’ then ‘+’ is not a unary operator because we used ‘+’ with two operands, so in this case, it is an addition operator that is adding two operands ‘5’ and ‘15’ and ‘y’ and ‘z’.

x = +5 # unary plus since used with only one operand 5

x = -5 # unary minus since used with only one operand 5

x = 5+8 # binary addition since used with two operands 5 and 8

x = 8-3 # binary subtraction since used with two operands 8 and 3

2.   Binary operators

Binary operators are operators who work on two operands. In binary, ‘bi’ means two. Following are binary operators in Python –

·         Arithmetic operators

·         Relational operators

·         Assignment operators

·         Logical operators

·         Bitwise operators

Arithmetic operators

These operators are used to perform mathematical or arithmetic calculations such as addition, subtraction, multiplication etc., that is why called arithmetic operators. Following table shows all arithmetic operators in Python –

Let’s assume that x = 9 and y =5

Operator

Meaning

Example

Result

+

Addition operator, adds two values

x + y

14

-

Subtraction operator, subtracts one value from another

x - y

4

*

Multiplication operator, multiplies two values

x * y

45

/

Division operator, divides left operand by the right and gives quotient

x / y

1.8

%

Modulus operator, divides left operand by the right and gives remainder

x % y

4

//

Integer or Floor division, divides left operand by the right and gives integer quotient only

x // y

1

**

Exponent operator, calculates power value. x**y gives the value of x to the power of y

x**y

59049

 

I think all operators are straightforward so there is no problem to understand it. But you may have some confusion in // and % operators. When we divide using // operator, then only integer part of the quotient is taken and rest is ignored. So you do not need to fully divide when using // operator. Just divide until you reach the complete integer part only. When we divide using % operator, then we get the remainder. While using % operator, do only integer division and get the remainder. Observe the code below –

print(25 // 7) # 3.5714 (here only 3 will be taken and rest will be ignored)

print(9 // 4) # 2.25 (here only 2 will be taken and rest will be ignored)

print(10 // 5) # 2

print(11 // 3) # 3

print(3//11) # 0 (since 3 of 11 runs 0 times)

print(3 % 11) # 3 (3 of 11 runs 0, so we get remainder 3# )

print(10 % 5) # 0

print(11 % 4) # 3 (do not divide completely just do an integer division)

Output –

3

2

2

3

0

3

0

3

Relational operators

These operators are used to compare two values. We all have used these operators in maths. For example, is 5 less than 9? Is 10 greater than 17? Is 8 equal to 8? Etc. are comparisons that can be done using relational operators. The result of a relational operator is always a Boolean value i.e. either True or False. So when we answer above questions then the result will be either Yes or No. So the results of those questions are – Yes, No, Yes respectively. In Python, our Yes or No values are represented as True or False. So Python will say either True or False. Simple? Following are relational operators available in Python –

Operator

Meaning

Example

Result

> 

Greater than operator

8 > 3

True

< 

Less than operator

34 < 8

False

>=

Greater than or equal to

8>=8

True

<=

Less than or equal to

10<=56

True

==

Equals to operator

9==13

False

!=

Not equals to operator

9!=13

True

 

Remember the statement ‘x>=y’ yields ‘True’ if ‘x’ is either greater than or equals to ‘y’. If any one of these conditions is True, then the result will be True. And if both the conditions are False then the result will be False. For example, in statement –

1 >= 7 # False

Is 1 greater than 7? – The answer is ‘No’

Or

Is 1 equal to 7? – The answer is ‘No’

So the result is False because both the conditions are False.

In statement –

1<=7 # True

Is 1 less than 7? – The answer is ‘Yes’

Or

Is 1 equal to 7? – The answer is ‘No’

So the result is True because one of the conditions is True.

And same concept happens with ‘<=’ operator. Now ‘==’ operator returns True if both the values are equal and returns False if values are not equal. For example –

5 == 5 # True

9 == 5 # False

-5 == -5 # True

-13 == 67 # False

Operator ‘!=’ behaves exactly opposite to ‘==’ operator. Operator ‘!=’ returns True if both values are not equal and returns False if both values are equal. Let’s take above statements again –

5 != 5 # False, because both values are equal

9 != 5 # True

-5 != -5 # False, because both values are equal

-13 != 67 # True

Assignment operators

‘=’ is called an assignment operator. It is used to assign the right side value to a left side variable. It’s very simple. We have used this operator in maths. It is exactly the same. For example –

x = 10 # assigns right side value 10 to left side variable ‘x’

We cannot write –

10 = x # error (left side must be a variable and not the value)

Compound assignment operators –

We can also use an assignment operator (=) with the combination of all the arithmetic operators (+, -, /, *, %, //, **). When assignment operator is used with arithmetic operators, then those operators are called compound assignment operators. Following are compound assignment operators –

Let’s assume the value of x = 10

 

Compound assignment Operator

Example

Meaning

Result

+=

x+=5

Adds 5 into variable x and stores the result into x, i.e. x=x+5

x = 15

-=

x-=5

subtracts 5 from variable x and stores the result into variable x, i.e. x=x-5

x = 5

*=

x*=5

multiplies 5 to variable x and stores the result into variable x, i.e. x=x*5

x = 50

/=

x/=5

divides 5 to  variable x and stores the quotient into variable x, i.e. x=x/5

x = 2.0

%=

x%=5

divides 5 to  variable x and stores the remainder into variable x, i.e. x=x%5

x = 0

//=

x//=5

divides 5 to  variable x and stores the integer quotient into variable x, i.e. x=x//5

x = 2

**=

x**=5

performs x to the power 5 and stores the result into variable x, i.e. x=x**5

x = 100000

 

Remember, unary + operator is written as ‘x=+5’ (‘=’ is written first, then ‘+’ operator) and compound assignment operator is written as ‘x+= 5’ (‘+’ operator written first, then ‘=’ operator) so don’t get confused. People always do mistakes by writing assignment operator first.

Examples in above table are called short hand notations or short forms of statements. Observe the statements below.

Short hand notation (compound statement)

Actual statement

x += y

x = x + y

x -= y

x = x - y

x *= y

x = x * y

x /= y

x = x / y

x %= y

x = x % y

x //= y

x = x // y

x **= y

x = x ** y

 

So we can write ‘short hand notation’ of an ‘actual statement’ using ‘compound assignment operators’. Observe the following questions –

Question: What is the short form or short hand notation of statement z = z + y?

Answer: z += y

Question: What is the actual statement of the short hand notation x /=y?

Answer: x = x/y

Logical operators

We know that what relational operators are. When a relational operator is used in any statement then, that statement is called a relational statement. A relational statement can also be called a condition since it checks for some condition. For example ‘x<y’ is a relational statement or a condition since it contains a relational operator ‘less than’ ( < ). Another examples of relational statements are: ‘x>y’, ‘x<=y’, ‘x>=y’, ‘x!=y’ and ‘x==y’. Like this, we also have ‘x+y’ an arithmetic statement since it contains an arithmetic operator. We also know that the result of a relational statement is either True or False.

x<y # a relational statement since we are asking Python, is x less than y?

Logical operators are mostly used to combine two or more relational statements. When two or more relational statements are combined together using logical operators then, that statement is called a logical statement. And result of a logical statement is also either True or False based on the results of relational statements. Observe the following concept where we are combining two relational statements with one logical operator –

As you can see we have combined two relational statements ‘x<y’ and ‘y>z’ with a logical operator. Both relational statements may give either True or False depending upon values of ‘x’ and ‘y’. And then these results i.e. True or False will be combined together with logical operator. And finally that logical statement will also give either True or False. There are three types of logical operators –

·         ‘and’ operator

·         ‘or’ operator

·         ‘not’ operator

‘and’ operator gives True if all the relational statements or conditions are True and if any single condition is False then, ‘and’ operator gives False. ‘Or’ operator gives True if any single relational statement or condition is True and it gives False if all the conditions are False. ‘not’ operator negates the result of a relational statement or condition i.e. True becomes False and False becomes True if there is a ‘not’ operator used. Observe the table below of logical operators –

Operator

Example

Meaning

Result

and

5 > 7 and 8 < 24

Since 1st condition is False, the overall result of the statement will be False because of ‘and’ operator, no need to check second condition

False

or

5 >7 or 8 < 24

1st condition is False, 2nd is True so the result will be True

True

not

not(5>7)

Since result of 5>7 is False, ‘not’ will make it True

True

 

As you can see, we need not check the other conditions in ‘and’ operator once we get a False condition. When we get at least 1 True condition in ‘or’ operator then we need not check the other conditions, the overall result will be True. And not operator reverses the result i.e. True becomes False and False becomes True. Let’s write some statements –

x=5

y=2

z=10

print(x>y and z<=x)

print(y<=x and z>=x)

print(x>y or z<=x)

print(x==y or z<=x)

print(not(y<=x and z>=x))

print(not(x==y or z<=x))

Output –

False

True

True

False

False

True

Bitwise operators

These operators are used to perform calculations on each bit i.e. 0 and 1 of a number, that is why called bitwise operators. Bitwise operators perform calculations on binary numbers only. Numbers we use in our daily life and in this book i.e. 0,1,2,3,4,5,6,7,8,9 are decimal numbers and numbers used by computers are binary numbers i.e. o and 1. Bitwise operators are used in hardware implementation (low level implementation) such as in memory, processor etc., since they work on binary bits.

We will perform bitwise operations on decimal numbers because Python made this easy for us but since bitwise operators work on only binary bits (0 and 1), those decimal numbers will be converted into binary numbers internally and then bitwise operations will be performed on binary numbers. Which means bitwise operations will be performed on binary numbers indirectly.

There are six types of bitwise operators –

·         Bitwise AND operator (&)

·         Bitwise OR operator (|)

·         Bitwise NOT or Complement operator (~)

·         Bitwise XOR operator (^)

·         Bitwise Left shift operator (<<)

·         Bitwise Right shift operator (>>) 

Bitwise AND operator (&)

Bitwise AND operator is represented through ‘&’ symbol. This operator does an AND operation on two bits. To understand how this operator works, observe the following table which is called a Truth table –

 

x

y

x&y

0

0

0

0

1

0

1

0

0

1

1

1

 

As we know that a binary number consists of only two values i.e. 0 and 1. And we also know that bitwise operators work on binary numbers only. For example, 0 & 0, 0 & 1, 1 & o etc. are bitwise operations. Since bitwise is a binary operator, it will work on two values or operands. That is why we took two operands ‘x’ and ‘y’ and all the possible values of these operands. Remember True is represented as 1 and False is represented as 0 in bitwise operations.

The result of a bitwise ‘&’ operator will be False or 0, if any one of the bits is 0 and result will be True or 1 if all the bits are 1. Observe the table, 0 & 0 = 0, 0 & 1 = 0, 1 & 0 = 0, 1 & 1 = 1 where left two values are values of operands ‘x’ and ‘y’ and right side is the result of operation ‘x & y’. So when the value is x=0 and y =0 we get x&y=0, when x=0 and y=1 we get x&y=0 and so on. This is how an ‘&’ operator works internally. But we will apply bitwise operators on decimal numbers and Python will tell the result in decimal also. for example –

If x = 5 and y = 3 then find x&y –

x = 5 # 0101 in binary

y = 3 # 0011 in binary

print(x&y)

# internal processing -

# 0101  

# & 0011

# do ‘&’ operation on each two bits

# 0&0=0, 1&0=0, 0&1=0, 1&1=1

# 0001 in binary

# 1 in decimal

Output –

1

Although we have applied ‘&’ operator on decimal numbers i.e. 5 and 3 but they got converted into binary numbers internally i.e. 0101 and 0011 and then bitwise operation was performed on these bits. Finally, Python again converted binary number 0001 into decimal 1 and displayed the result.

If you know how decimal and binary numbers are converted into each other then it is good and if you don’t know then please observe the table below which shows the binary equivalent of decimal numbers and vice versa.

 

Decimal number

Binary equivalent

0

0000

1

0001

2

0010

3

0011

4

0100

5

0101

6

0110

7

0111

8

1000

9

1001

Bitwise OR operator (|)

‘|’ symbol is used to represent bitwise OR operator. This operator performs an OR operation on binary bits. See the table below of OR operations –

 

x

y

x|y

0

0

0

0

1

1

1

0

1

1

1

1

 

The result of a bitwise OR operator will be False or 0, if all the bits are 0 and result will be True or 1 if any one of the bits is 1. See the above code again with a bitwise OR operator –

x = 5 # 0101 in binary

y = 3 # 0011 in binary

print(x|y)

# internal processing

#    0101

#  | 0011

# do OR operation on each bit

# 0|0=0, 1|0=1, 0|1=1, 1|1=1

# 0111 in binary

# 7 in decimal

Output –

7

Bitwise NOT operator (~)

‘~’ (a tilde) symbol represents bitwise NOT operator. This operator negates the bits of a number i.e. it converts 1 into 0 and 0 into 1. This operator makes 1’s complement of a binary number. 1’s complement means bits that are 0 become 1 and, those that are 1 become 0. Let’s take an example –

x = 5 # 0000 0101 in binary

print(~x) # will complement the number

# internal processing -

# 0000 0101 will become 1111 1010

# it is nothing but -6 in decimal

Output –

-6

Bitwise XOR operator (^)

‘^’ symbol represents an XOR operator. This operator performs an XOR operation on binary bits. Se the following Truth table –

 

x

y

x^y

0

0

0

0

1

1

1

0

1

1

1

0

 

The result of a bitwise XOR operator will be False or 0, if all the bits are either 0 or 1 and result will be True or 1 if one bit is 1 and other bit is 0. See the above code again with a bitwise XOR operator –

x = 5 # 0101 in binary

y = 3 # 0011 in binary

print(x^y)

# internal processing

#  0101 

# ^0011

# do XOR operation on each bit

# 0^0=0, 1^0=1, 0^1=1, 1^1=0

# 0110 in binary

# 6 in decimal

Output –

6

Bitwise left shift operator (<<)

This operator shifts the bits of the number towards left a specified number of positions. Left and right shift operators are used to extract bits from a number. Example to use this operator is –

x << 2

where ‘x’ is the number whose bits we want to shift and 2 is the number of shift positions i.e. shift ‘x’ to 2 bits left. Again, number ‘x’ will be converted into binary first then ‘x’ will be shifted to 2 bits left. Let’s take an example where x = 4, 4 in binary is 0100, see the table. Since there are only 4 bits in the number, we will take total 8 bits by placing 0 at the beginning of the bits i.e. 0000 0100. So now number 4 = 0000 0100 (it does not matter if we put 0 at starting of a number)

x = 4 # 0000 0100 in binary

y = x << 2 # shifting 0000 0100 two bits left, y = 00010000 i.e. 16 in decimal

print(y) # printing contents of y

Output –

16

Shifting 2 bits left means, remove left 2 bits and shift the remaining bits to the left and fill two 0s at the right side to make it an 8-bit number. The image below will clear your doubts –

As you can see when we shifted number 4 to 2 bits left then, the left 2 bits were removed and remaining bits were shifted towards left. The other two empty bits were filled by two 0s. The number we got after shifting 00010000 is nothing but 16 in decimal.  

Bitwise right shift operator (>>)

This operator works exactly same as left shift operator, the only difference is that right shift operator shifts the bits of the number towards right a specified number of positions. let’s take an example –

Observe the code below –

x = 4 # 0000 0100 in binary

y = x >> 2 #shifting 0000 0100 two bits right, y = 0000 00001 i.e. 1 in decimal

print(y) # printing contents of y

Output –

1

As you can see when we shifted number 4 to 2 bits right then, the right 2 bits were removed and remaining bits were shifted towards right. The other two empty bits were filled by two 0s. the number we got after shifting 00000001 is nothing but 1 in decimal.

Comments

Popular posts from this blog

Python 4.4 - Points to remember

Python 3.6 - Points to remember

Python 3.3 - Datatypes in Python