Operators and Expressions: Prof. Rajiv Kumar IIM Kashipur
Operators and Expressions: Prof. Rajiv Kumar IIM Kashipur
Operators and Expressions: Prof. Rajiv Kumar IIM Kashipur
Source:
Kamthane, A. N. & Kamthane, A.A., Programming and Problem Solving with Python, Tata McGraw-Hill
Education India. & from various sources
Introduction to Expression and Operators
An expression in Python is a block of code that produces a result or value upon evaluation.
Operators are symbols help the user or command computer to perform mathematical operations.
Example:
In the expression 6 + 3 the ‘+’ act as operator. Where operator requires operands to perform
operations. Therefore 6 and 3 act as operands.
Arithmetic Operators
There are two types of Arithmetic Operators
a) Unary Operator
b) Binary Operator
Unary Operators:
Unary arithmetic operators perform mathematical operations on one operand only. The ‘+’ and ‘-’ are two unary operators.
Example:
>>> x = -5 #Negates the value of X
>>> x
-5
Binary Operators
Binary operators are operators which require two operands .
Operator is written in between two operands.
Example:
>>> 3 + 10
>>>13
>>> 10 – 7
>>> 3
Division(/) Operators and Floor Division Operators
Division Operator
If the division operator is applied in between two operands, it returns the result as the arithmetic quotient of the
operands.
Example:
>>> 4/2
>>> 2.0
>>> 2/3
0.6666666666666666
Floor Division (//) Operator
If the floor division operator is applied in between two operands, it returns the result as the arithmetic
quotient of the operands .
Python floor division (//) operator when applied on two int operands, Python returns an int result.
Example:
>>> 9//4
2
Modulo (%) Operator
When the second number divides the first number, the modulo operator returns the remainder.
Example:
>>> 21 % 9
3
Note:
X%Y is equivalent to X – Y * (x//Y)
The Exponent ** Operator
The ‘**’ exponent operator is used to calculate the power or exponent of a number
Example
>>> 5**4
625
Operator Precedence and Associativity
The operator precedence determines the order in which the python interpreter evaluates the operators in
an expression.
a) Left to Right
Example:
4+6–3+2 = 9
Note: When the operators of same priority are found in the expression, precedence is given to the left most
operator.
b) Right to Left
X = Y = Z = Value
Note: When the operators of same priority are found in the expression, precedence is given to the right
most operator.
Associativity Continued….
Example:
Z = 4 * 6 + 8 // 2
= 28
In the above expression * is evaluated first, even though * and // have the same priorities. The operator *
occurs before // and hence the evaluation starts from left to right.
Example:
X=X+1
X+=1
Various binary operators such as addition (+), subtraction (-), multiplication (*), integer division, floor
division, modulus operators (%), and exponent (**) are covered.