Python LEC 3 Operators
Python LEC 3 Operators
Lecture# 3
Lecture Content
1. Operators And Operands
2. Types Of Operators
3. Associativity Rule
4. Type Casting
5. Example(s)
Operators And Operands:
Operators are used to performing operations on variables and values while
Operands refer to the values on which the operator operates.
Types Of Operators:
There are 7 different types of operators in python. However, we’ll discuss 4 of
them which are listed below:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Arithmetic Operators:
Arithmetic operators are used to performing mathematical operations like addition,
subtraction, multiplication, etc. Arithmetic operators are listed below:
Suppose a=5,
b=2
Example:
Create 2 variables a and b and assign values to them. After assigning values to
variables perform arithmetic operations on it.
Assignment Operators:
Assignment operators are used to assign values to variables. Assignment Variables
are shown below:
Example:
a = 10 # assign 10 to a
b = 5 # assign 5 to b
print(a)
# Output: 15
Comparison Operators:
A comparison operator, also called the python relational operator compares two
values/variables and returns a Boolean result either True or False. Comparison
operators are used in decision-making and loops.
Logical Operators:
Logical operators are used to checking whether an expression is True or False.
They are used in decision-making.
Operator Precedence:
Operator precedence simply refers to the order of operations.
Precedence Operator Associativity
7 () Left to Right
6 ** Right to Left
5 * Left to Right
/
%
4 + Left to Right
-
3 not Left to Right
2 and Left to Right
1 or Left to Right
Let's try to solve this expression by breaking it out and applying the precedence
and associativity rule.
The interpreter encounters the parenthesis (. Hence it will be
evaluated first.
Later there are four operators +, −, * and /.
Precedence of (/, and *) > Precedence of (+, -).
Associativity rule will be followed for operators with the same
precedence.
This expression will be evaluated from left to right, 9 / 3 * 7 = 3 * 7 = 21.
Now, our expression has become 43+13-21.
Left to right Associativity rule will be followed again. So, our final
value of the expression will be, 43+13-21 = 56-21 = 35.
Exercise:
1. Make a calculator by using input and variables concept for performing addition,
subtraction, multiplication and division