0% found this document useful (0 votes)
0 views50 pages

lecture 4 operators python

The document provides an overview of operators in Python, categorizing them into arithmetic, assignment, unary, relational, logical, boolean, bitwise, membership, and identity operators. It explains the purpose and functionality of each operator type, including examples of their usage and the results of various operations. Additionally, it discusses the order of operations and how to use Python as a calculator for basic arithmetic calculations.

Uploaded by

kumud yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views50 pages

lecture 4 operators python

The document provides an overview of operators in Python, categorizing them into arithmetic, assignment, unary, relational, logical, boolean, bitwise, membership, and identity operators. It explains the purpose and functionality of each operator type, including examples of their usage and the results of various operations. Additionally, it discusses the order of operations and how to use Python as a calculator for basic arithmetic calculations.

Uploaded by

kumud yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Lecture 4

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

operator meaning example result


+ Addition operator. Add two Values a+b 18

- Subtraction operator. Subtracts one value a-b 8


from another
* Multiplication operator. Multiplies values a*b 65
on either side of operator
/ Division operator. Divides left operand by a/b 2.6
the right operand
% Modulus operator. Gives reminder of a%b 3
division
** Exponent operator. Calculate exponential a**b 37129
power value. a**b gives value of a to
power of b
// Integer division. This is also called Floor a//b 2
division. Performs division and gives only
integer quotient
Arithmetic Operators
• When there is expression that contains several arithmetic opeartors in
such case following order of evaluation is used:
• First parentheses are evaluated
• Exponentiation is done next
• Multiplication division modulus and floor divisions are at equal priority
• Addition and subtraction are done afterwards
• Finally assignment operation is performed
Arithmetic Operators
• Let’s take sample expression:
• d = (x+y)*z**a//b+c
• Assume values of variables as: x =1; y = 2; z = 3; a = 2; b = 2; c = 3
• Given expression d = (1+2)*3**2//2+3 will evaluate as:
1. First parentheses are evaluated d = 3*3**2//2+3
2. Exponentiation is done next d = 3*9//2+3
3. Multiplication division modulus and floor divisions are at equal priority
d = 27//2+3 and than d = 13+3
4. Addition and subtraction are done afterwards d =16
5. Finally assignment is performed
6. Value 16 is now stored into d
Using Python Interpreter as
Calculator
• Python Interpreter can be used as simple calculator that can perform
basic arithmetic calculations
• Arithmetic operations can be performed in python IDLE
• >>>13+5
• 18
• >>>13-5
•8
• >>>13*5
• 65
• >>>13/5
•3
Assignment Operators
• These operators are useful to store right side value into left side
variable
• They can be used to perform simple arithmetic operation like addition
subtraction etc. and then store result into variable
Assignment Operators
• Let’s assume values x =20 y =10 and z = 5:
operator example Meaning Result
= z=x+y Assignment operator. Stores right side value into left side variable. i.e x+y is stored into z z-=30

+= 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

operator example meaning result


And x and y And operator. If x is False it returns x otherwise it returns 2
y
Or x or y Or operator. If x is False it returns y otherwise it return x 1

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

operator example meaning result


and x and y Boolean and operator. If both x and y are True then it False
returns True otherwise False
or x or y Boolean or operator. If either x or y is True then it True
returns True else False
not not x Boolean not operator. If x is True it returns False else False
True
Bitwise Operators
• These operators act on individual bits 0 and 1 of operands
• Bitwise operators can directly be used on binary numbers or inegers
also
• When these operators are used on integers these numbers are
converted into bits and bitwise operators act upon those bits
• Results given by these operators are always in form of integers
Bitwise Operators
• There are 6 types of bitwise operators as shown below:
Bitwise Complement operator ~
Bitwise AND operator &
Bitwise OR operator |
Bitwise XOR operator ^
Bitwise left shift operator <<
Bitwise Right shift operator >>
Bitwise Complement Operator ~
• This operator gives complement form of given number
• Operator symbol is ~ which is pounced as tilde
• Complement form of positive number can be obtained by changing
0’s and 1’s and vice versa
• Complement operation is performed by Not gate circuit in electronics
• Truth table is table that gives relationship between inputs and outputs
Bitwise Complement Operator ~
• Truth table of not NOT gate

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy