Skip to main content

Operators, Precedence and Expression Evaluation

Operators are special symbols which represents computation. They are applied on operand(s), which can be values(constants) or variables. Same operator can behave differently on different data types. Operators when applied on operands form an expression Operators are categorized as

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

Arithmetic Operators( Mathematical)

Symbol

Description

Example 1

Example 2

+

Addition

>>>55+45
100

>>> “Good” + “Morning”
GoodMorning

 

-

 

Subtraction

>>>55-45
10

>>>30-80
-50

 

*

 

Multiplication

>>>55*45
2475

>>> “Good” * 3
GoodGoodGood

 

/

 

Division

>>>17/5
3
>>>17/5.0
3.4

>>> 17.0/5
3.4
>>>28/3
9

 

%

 

Remainder/
Modulo

>>>17%5
2

>>> 23%2
1

 

**

 

Exponentiation

>>>2**3
8
>>>16**0.5
4.0

>>>2**8
256

 

//

 

Integer
Division

>>>7.0//2
3.0

>>>3/ / 2
1                                      


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

Symbol

Description

Example 1

Example 2

Less than

>>>7<10
True

>>>'Goodbye' < 'Hello'
True

Greater than

>>>7>5
True

>>>'Goodbye' > 'Hello'
False

<=

less than equal to

>>> 2<=5
True

>>>"Hello" <= “Goodbye”
False

>=

greater than equal
to

>>>10>=10
True

>>>"Hello" >= “Goodbye”
True

! =

not equal to

>>>10!=11
True

>>>‟Hello”!= “HELLO"
True

==

equal to

>>>10==10
True

>>>"Hello" == “Hello”
True

Note: two values that are of different data type will never be equal to each other.

Assignment Operators
Assignment Operator combines the effect of arithmetic and assignment operator

Symbol

Description

Example

Explanation

 

=

Assigned values from right side
operands to left variable

>>>x=12
>>>y="greetings"

x=12

( we will assume x=12 for all examples)

 

+= 

 

added and assign back the result
to left operand

>>>x+=2

x=x+2
x=14

 

-=

subtracted and assign back the
result to left operand

x-=2

x will become 10

 

*=

multiplied and assign back the
result to left operand

x*=2

x will become 24

 

/=

divided and assign back the

result to left operand

x/=2

x will become 6

 

 

%=

taken modulus using two
operands and assign the result
to left operand

 

x%=2

 

x will become 0

 

 

**=

performed exponential (power)
calculation on operators and
assign value to the left operand

x**=2

x will become 144

 

//=

performed floor division on
operators and assign value to
the left operand

x / /= 2

x will become


Logical Operators 

The following logical operators are supported by Python language. Assume variable A holds True and variable B holds False.
SymbolDescriptionExample
orIf any one of the operand is true, then the condition becomes true.A or B is True
andIf both the operands are true, then the condition becomes true.A and B is False
notReverses the state of operand/condition.not A is False
 

Python Bitwise Operators

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows −

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

Python's built-in function bin() can be used to obtain binary representation of an integer number.

The following Bitwise operators are supported by Python language 

Operator

Description

Example

& Binary AND

Operator copies a bit, to the result, if it exists in both operands

(a & b) (means 0000 1100)

| Binary OR

It copies a bit, if it exists in either operand.

(a | b) = 61 (means 0011 1101)

^ Binary XOR

It copies the bit, if it is set in one operand but not both.

(a ^ b) = 49 (means 0011 0001)

~ Binary Ones Complement

It is unary and has the effect of 'flipping' bits.

(~a ) = -61 (means 1100 0011 in 2's complement form due to a signed binary number.

<< Binary Left Shift

The left operand's value is moved left by the number of bits specified by the right operand.

a << 2 = 240 (means 1111 0000)

>> Binary Right Shift

The left operand's value is moved right by the number of bits specified by the right operand.

a >> 2 = 15 (means 0000 1111)


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

Let  S=”Python”  c=’o’

Operator

Description

Example

in

Evaluates to true if it finds a variable in the specified sequence and false otherwise.

 in S will result True

not in

Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.

c not in S will result False


Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity operators as explained below

Let x=10 and y=x

id(x) and id(y) are same in this case

Operator

Description

Example

is

Evaluates to true if the variables on either side of the operator point to the same object and false otherwise.

x is y will return True

is not

Evaluates to false if the variables on either side of the operator point to the same object and true otherwise.

x is not y will return False

 Operators Precedence

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

Sr.No.

Operator & Description

1

**

Exponentiation (raise to the power)

2

~ + -

Complement, unary plus and minus

3

* / % //

Multiply, divide, modulo and floor division

4

+ -

Addition and subtraction

5

>>    <<

Right and left bitwise shift

6

&

Bitwise 'AND'

7

^ |

Bitwise exclusive `OR' and regular `OR'

8

<=        >=

Comparison operators


Arithmetic Expressions and Evaluation

When we have an expression consisting of several operators how does Python decide the order of operations? It is done based on precedence of operator. Higher precedence operator is worked on before lower precedence operator.

Operator associativity determines the order of evaluation when they are of same precedence and are not grouped by parenthesis. Parenthesis has high precedence.

An operator may be Left-associative or Right –associative. In left associative, the operator falling on left side will be evaluated first, while in right assosiative operator falling on right will be evaluated first.


Note: In python “=” and “**” are Right Associative.Other operators are left associative means they are evaluated from left to right.
Examples:
>>>2+3**2 
11
here 3**2 will be evaluated first because it is having high precedence. So 2+9=11 will be the result.

>>>2**3**2
512
Here 3**2 will be evaluated first because the associativity is from right to left. So 2**9=512 will be the result.>>>-4**2 # here unary operator applied later
-16
>>4%0
This will produce division by zero exception
>>>2+3/2*4**2
18
Here the sub expression 4**2 will be evaluated first because ** having high precedence. So the expression becomes 2+3/2*16. Now we have two operators / and * having same precedence. The associativity is from left to right so division will be done first. The expression become 2 + 1 * 16 after integer division. Now we have two operators + and * .But * is having high precedence so multiplication will be done first followed by the addition and the final result become 18.
>>2*3//2+3/2
4.5

Try your own examples....

Comments

Popular posts from this blog

Classes and Objects in Python

Python is an object-oriented programming language, which means that it provides features that support object-oriented programming. The basic components of object oriented programming are classes and objects. A Class is a blue print to create an object. It provides the definition of basic attributes and functions of objects. Object is a running instance of the class having the identity(name), properties( values) and behaviors(functions). The Object oriented program thus consist of object definitions (classes) and most of the computations and functions are mentioned as operations on the object. Each object definition corresponds to some object or concept in the real world, and the functions that operate on these object correspond to the ways real-world objects interact. We have learned objects of string, list, tuple etc…and used the properties and functionalities of these objects which are built into the Python. Now we are going to create our own(user defined) objects. Th

Identifiers,Variables and Keywords

Identifiers An identifier is a name given to entities like variables,functions,class, functions etc. It helps to differentiate one entity from another. Rules for writing identifiers 1.Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _.  Names like myClass, var_1 and print_this_to_screen, all are valid example. 2.An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name. 3.Keywords cannot be used as identifiers. Eg: global = 1 is invalid 4.We cannot use special symbols like !, @, #, $, % etc. in our identifier. a@=0 is invalid 5.An identifier can be of any length. Things to Remember Python is a case-sensitive language. This means, Variable and variable are not the same. Always give the identifiers a name that makes sense. While c = 10 is a valid name, writing count=10 would make more sense, and it would be easier to figure out what it represents when you look at your code after

Files in Python , Exception handling

While a program is running, its data is in main memory. When the program ends, or the computer shuts down, data in memory disappears. To store data permanently, you have to put it in a file. Files are usually stored on a secondary storage device(hard disk, pen drive, DVD,CD etc).  When there are a large number of files, they are often organized into directories (also called “folders”). Each file is identified by a unique name, or a combination of a file name and a directory name.  By reading and writing files, programs can exchange information with each other and generate printable formats like PDF. Working with files is a lot like working with books. To use a book, you have to open it. When you’re done, you have to close it. While the book is open, you can either write in it or read from it. In either case, you know where you are in the book. Most of the time, you read the whole book in its natural order, but you can also skip around. All of this applies to files as well.