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
Relational
Logical
Assignment.

Mathematical/Arithmetic Operators

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**.5
4.0

>>>2**8
256
//

Integer
Division

>>>7.0//2
3.0

>>>3/ / 2
1

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.

Logical Operators

Symbol
Description
or
If any one of the operand is true, then the condition becomes true.
and
If both the operands are true, then the condition becomes true.
not
Reverses the state of operand/condition.

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

+=


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 6

Note:
1. Same operator may perform a different function depending on the data type of
the value to which it is applied.
Eg: print “python”*3  will print pythonpythonpython
      print 2*3  will print 6.
2. Division operator  “/ behaves differently on integer and float values
Eg; print 3/2 will print 1
      print 3.0/2 will print 1.5

Expressions

Expressions are combinations of values ( constants) variables and operators.
Eg: 2+ x * y
       math.pi * r ** 2

An expression in which different data types are used is called mixed type expression.
Eg: 3.5/2+(6.4-2)

When mixed type expressions are evaluated, Python promotes the result of lower data type to higher data type( i.e. to float in the above example). This automatic type conversion is known as implicit type casting or coercion. For the mathematical operators, if either operand is a float, the other is automatically converted to a float.
Eg: >>>1/2               >>>1.0/2
0                      0.5      

We can also convert one data type into another using explicit type conversion. Python provides built in functions to convert one type to another.
Eg: >>>1/2               >>>float(1)/2
            0                      0.5

int function can convert string and float to integers
>>> int(3.99999)
3
>>> int(-2.3)
-2
>>> int("32")
32

The float function converts integers and strings to floating-point numbers:
>>> float(32)
32.0
>>> float("3.14159")
3.14159
Finally, the str function converts to type string:
>>> str(32)
’32’
>>> str(3.14149)
’3.14149’

Note: It may seem odd that Python distinguishes the integer value 1 from the floating point value 1.0. They may represent the same number, but they belong to different types. The reason is that they are represented differently inside the computer.

Operator precedence

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.

Precedence of operator - Listed from high precedence to low precedence.

Operator                                           Description
**                                                         Exponentiation (raise to the power)
+ , -                                                     Unary plus and minus
* , /, %, //                                         Multiply, divide, modulo and floor division
+ , -                                                     Addition and subtraction
<, <=, >, >=                                       Comparison operators
==, !=                                                  Equality operators
% =, / =, // = , -=,+=,*=                 Assignment operators
not and or                                          Logical operators

Note: Remember precedence of operators is applied to find out which sub expression
should be evaluated first.
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.

>>>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.

Popular posts from this blog

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. To open a fil…

User Defined Functions in Python

So far we have only seen the functions which come with Python either in some file (module) or in interpreter itself (built in), but it is also possible for programmer to write their own function(s) and are called User Defined Functions. These functions can then be combined to form a module which can then be used in other programs by importing them.
In the context of programming, a function is a named sequence of statements that performs a desired operation. This operation is specified in a function definition.
To define a function keyword def is used. After the keyword comes an identifier i.e.name of the function, followed by parenthesized list of parameters and the colon which ends up the line. Next follows the block of statement(s) that are the part of function. A block is one or more lines of code, grouped together so that they are treated as one big sequence of statements while executing. In Python, statements in a block are written with indentation. Usually, a block begins when a li…

Dictionary In Python

Dictionaries are similar to other compound types except that they can use any immutable type as an index. We can refer to a dictionary as a mapping between a set of indices (which are called keys) and a set of values. Each key maps a value. The association of a key and a value is called a key-value pair. A dictionary is an extremely useful data storage construct for storing and retrieving all key value pairs, where each element is accessed (or indexed) by a unique key. However, dictionary keys are not in sequences.
            Dictionaries are mutable.             Dictionaries are unordered. Items in dictionaries are accessed via keys and not via their position. A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated (or mapped) to a value. The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-pairs.  Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and…