lecture 4 operators python
lecture 4 operators python
Operators in python
By
Dr. Sunita Varma
Operators
• General purpose of program is to accept data and perform some
operations on data
• Data in program is stored in variables
• Next question is how to perform operations on data
• For example when programmer wants to add two numbers he can
simply type + symbol
• This symbol preforms addition operation
• Such symbols are called operators
Operators
• Operator is symbol that performs operation
• Operators acts on some variables called operands
• For example if a + b is written operator + is acting on two operands a
and b
• If operator acts on single variable is called unary operator
• If operators act on two variables it is called binary operator
• If operators act on three variables it is called ternary operators
Operators
• Another classification of operators is based on nature of operators
which is as follows:
Arithmetic operators
Assignment operators
Unary operators
Relational operators
Logical operators
Boolean operators
Bitwise operators
Membership operators
Identity operators
Arithmetic Operators
• These operators are used to performs basic arithmetic operations like
addition subtraction division etc.
• There are seven arithmetic operators available in python
• These operators act on two operands they are called binary operators
Arithmetic Operators
• Let’s assume a = 13 and b = 5
+= z+=x Addition assignment operator. Adds right operands to left operand and stores result into left operand z=25
i.e. z = z+x
-= z-=x Subtraction assignment operator. Subtracts right operand from left operand and stores result into left z=-15
operand i.e z = z-x
*= z*=x Multiplication assignment operator. Multiplies right operand with left operand and stores result into z=100
left operand i.e. z = z*x
/= z/=x Division assignment operator. Divides left operand with right operand and stores result into left z = 0.25
operand i.e. z = z/x
%= z%=x Modulus assignment operator. Divides left operand with right operand and stores reminder into left z=5
operand i.e. z = z%x
Z**=y Exponentiation assignment operator. Performs power value and then stores result into left operand z=0765625
**= i.e. z=z**y
//= z//=y Floor division assignment operator. performs floor division and then stores result into left operand z=0
i.e. z=z//y
Assignment Operators
• It is possible to assign same value to two variables in same statement
as
• a=b=1
• Print(a,b)
• Different values are assigned to two different variables
• a = 1; b =2
• Print(a,b)
• Same can be done using following statement
• a, b = 1, 2
• Python does not have increment operator (++) and decrement
operator(--) that are available in C and Java
Unary Minus Operator
• Unary minus operator is denoted by symbol minus –
• When this operator is used before variable its value is negated
• That means if variable is positive it will be converted into negative and
vice versa
• n = 10
Print(-n)
num = -10
num = -num
Print(num)
Relational Operators
• Relational operators are used to compare two quantities
• Whether two values are same or which one is bigger or which one is
lesser using theses operators
• These operators will result in True or False depending on values
compared
Relational Operators
operator example meaning Result
> a>b Greater than operator. If value of left operand is greater than value of right operand it False
gives True else it gives False
>= a>=b Greater than or equal operator. If value of left operand is greater or equal than that of False
right operand it gives True else False
< a<b Less than operator. If value of left operand is less than value of right operand it gives True
True else gives False
<= a<=b Less than or equal operator. If value of left operand is lesser or equal than that of right True
operand it gives True else False
== a==b Equals operator. If value of left operand is equal to value of right operand it gives True False
else False
!= a!=b Not equals operator. If value of left operand is not equal to value of right operand it True
returns True else it returns False
Relational Operators
• Relational operators are generally used to construct conditions in if
statements
• a = 1; b =2
• if (a>b):
Print(“yes”)
• else:
Print(“no”)
Logical Operators
• Logical operators are useful to construct compound conditions
• Compound condition is combination of more than one simple
condition
• Each of simple condition is evaluated to True or False and then
decision is taken to know whether total condition is True or False
• In case of logical operators False indicates 0 and True indicates any
other number
Logical Operators
• Let’s take x =1 and y = 2
Not not x Not operator. If x is False it returns True otherwise True False
Logical Operators
• X = 100
• Y = 200
• Print(x and y)
• Print(x or y)
• Print(not x)
• x = 1; y = 2; z = 3
• if(x<y and y<z): print(‘yes’)
• else: print(‘No’)
• if(x>y or y<z): print(‘yes’)
• else: print(‘no’)
Boolean Operators
• There are two bool type literals True and False
• Boolean operators act upon bool type literals and they provide bool
type output
• Result provided by Boolean operators will be again wither True or
false
Boolean Operators
• Let’s take x = True and y = False
x y
0 1
1 0
Bitwise Complement Operator ~
• If x = 10 find ~x value
• X = 10 = 0000 1010
• By changing 0’s as 1’s and vice versa result is 1111 0101
• This is -11 or ~x = -11
Bitwise AND Operator &
• Operator performs AND operation on individual bits of numbers
• Symbol for this operator is & which is called ampersand &
• Truth table of AND operator is as follows:
x y X&y
0 0 0
0 1 0
1 0 0
1 1 1
Bitwise AND Operator &
• Truth table shows that multiplying input bits gives output bits
• AND gate circuit present in computer chip will perform AND operation
• If x =10, y = 11 Find value of x&y
• x = 10 =0000 1010
• y = 11 = 0000 1011
• From truth table by multiplying bits x7y = 0000 1010
• This is decimal 10
Bitwise OR Operator |
• Operator performs OR operation on bits of numbers
• Symbol of bitwise OR operator is | which is called pipe sysmbol
• Truth table of OR operation is as follows:
x y x|y
0 0 0
0 1 1
1 0 1
1 1 1
Bitwise OR Operator |
• Adding input bits give output bits in OR operation
• OR gate circuit which is present in computer chip will perform OR
operation
• If x = 10, y = 11 find value of x|y
• x = 10 = 0000 0101
• y = 11 = 0000 1011
• Turuth table shows adding bits give x|y = 0000 1011
• This is decimal 11
Bitwise XOR Operator ^
• This operator performs exclusive or XOR operation on bits of
numbers
• Symbol is ^ which is called cap carat or circumflex symbol
• Truth table of XOR operation is as follows:
x y x^y
0 0 0
0 1 1
1 0 1
1 1 0
Bitwise OR Operator |
• XOR gate circuit of computer chip will perform this operation
• If x= 10, y = 11 find value of x^y
• x = 10 =0000 1010
• y = 11 = 0000 1011
• From truth table output of x^y is 0000 0001 which is decimal 1
Bitwise Left Shift Operator <<
• This operator shifts bits of number towards left specified number of
positions
• Symbol for this purpose operator is << read as double less than
• x<<n means shift x towards left n positions
• If x = 10 calculate x value if x<<2
• Shifting value x towards left 2 positions will make leftmost 2 bits to be
lost
• Value of x is 10 = 0000 1010
• Now x<<2 will be 0010 1000 = 40
Bitwise Right Shift Operator >>
• This operator shifts bits of number towards right specified number of
positions
• Symbol for this operator is >> read as double greater than
• x>>n meaning is to shift bits towards right n positions
• >> shifts bits towards right and also preserves sign bit which is
leftmost bit
• Sign bit represents sign of number
• Sign o presnts a positive number and 1 represents negative number
• After performing >> operation on positive number gives positive value
and right on negative number gives negative number
Bitwise Right Shift Operator >>
• If x = 10 then calculate x>>2 value
• Shifting value x towards right 2 positions will make rightmost 2 bits to
be lost
• x value is 10 = 0000 1010
• Now x>>2 will be 0000 0010 =2 decimal
Membership operators
• Membership operators are useful to test for membership in sequence
such as strings lists tuples dictionaries
• For example if an element is found in sequence or not can be asserted
using these operators
• There are two membership operators
in
not in
in Operator
• This operator returns True if element is found in specified sequence
• If element is not found in sequence then it returns False
• Let’s take group of strigs in list
• Display members of list using for lop where in operator is used
• List of name is given below:
• names = [“Rani”, “Yamini”, “Sushmita”, “Veena”]
• for name in names:
print(name)
not in Operator
• This operator returns True if element is not found in sequence
• If element is found in sequence then it returns False
Identity Operators
• These operators compare memory locations of two objects
• It is possible to know whether two objects are same or not
• Memory location of object can be seen using id() function
• This function returns integer number called identity number internally
represents memory location of object
• For example id(a) gives identity number of object referred by name a
• a = 25
• b = 25
• Id(a)
• 1670954952
• Id(b)
• 1670954952
Identity Operators
• There are two identity operators:
is
is not
is Operator
• Is operator is useful to compare whether two objects are same or not
• It will internally compare identity number of objects
• If identity numbers of objects are same it will return True otherwise it
return False
Identity Operators
• a = 25
• b = 25
• if (a is b):
print(‘a and b have same identity”)
• else:
print(“a and b do not have same identity)
Identity Operators
• one = [1,2,3,4]
• two = [1,2,3,4]
• if(one is two)
print(“one and two are same”)
• else:
print(“one and two are not same”)
Operator Precedence and
Associativity
• Expression or formula may contain several operators
• Sequence of execution of operators is called operator precedence
• Precedence represents priority level of operator
• Operator with higher precedence will be executed first than lower
precedence
• If expression contains operators having same precedence then order
of execution is decided by associativity
• Associativity is order in which expression is evaluated that has
multiple operators of same precedence
• Almost all opertors are left-to-right associativity in python
Operator Precedence and
Associativity
Operator Name
() parenthesis
** Exponentiation
-, ~ Unary minus, Bitwise complement
*, /, //, % Multiplication, Division, Floor division, Modulus
+, - Addition, Subtraction
<<, >> Bitwise left shift, Bitwise right shift
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
>, >=, <, <=. ==, != Relational operators
=, %=, /=, //=, -=, +=, *=, **= Assignment operators
Is, is not Identity operators
In, not in Membership operators
Not Logical not
or Logical or
and Logical and
Mathematical Functions
• Built-in functions can be used in python to perform various advanced
operations
• For example to calculate square root value of number sqrt() function
that is already given in math module can be used
• To calculate square root of 16 sqrt(16) can be called
• In python module is file that contains group of useful objects like
functions classes or variables
• math is module that contains several functions to perform
mathematical operations
• For using module in python program first module is imported into
program by writing import statement
Mathematical Functions
• For example to import math module
• Import math
• Once module is imported in any function available in module can be called in
program
• x = math.sqrt(16)
• Or
• Import math as m
• x = m.sqrt(16)
• Or
• from math import sqrt
• x = sqrt(16)
• Or
• From math import factorial, sqrt
• x = sqrt(16)
• y = factorial(5)
Using IDLE Window
• Click on Python IDLE window icon available at task bar
• This will open Python Shell window where user should type program
• When last statement is typed and Enter is pressed result will be
displayed
Using Command Line Window
• Click on Python command line window icon available at task bar
• This will open Python command line window where user should type
program
• When last statement is typed and Enter is pressed result will be
displayed
Executing at System Prompt
• Open text editor like Notepad or Edit Plus and then type program
• Save program as filename.py in directory
• Open command prompt window and go to that directory where
program is stored
• Then invoke python interpreter by typing
• c:\username>filename.py