Leela Soft Python Madhu B
Operators in Python
Operator is a symbol that performs certain operations.
Python provides the following set of operators
1. Arithmetic Operators
2. Relational Operators or Comparison Operators
3. Logical operators
4. Bitwise operators
5. Assignment operators
6. Special operators
1. Arithmetic Operators:
+ ==>Addition
- ==>Subtraction
* ==>Multiplication
/ ==>Division operator
% ===>Modulo operator
// ==>Floor Division operator
** ==>Exponent operator or power operator
Example 1: test.py:
a=10
b=2
print('a+b=',a+b)
print('a-b=',a-b)
print('a*b=',a*b)
print('a/b=',a/b)
print('a//b=',a//b)
print('a%b=',a%b)
print('a**b=',a**b)
Output:
python test.py or py test.py
a+b= 12
a-b= 8
a*b= 20
a/b= 5.0
a//b= 5
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
a%b= 0
a**b= 100
Example 2: test.py
a=10.5
b=2
print('a+b=', a+b)
print('a-b=', a-b)
print('a*b=', a*b)
print('a/b=', a/b)
print('a//b=', a//b)
print('a%b=', a%b)
print('a**b=', a**b)
Output:
python test.py or py test.py
a+b= 12.5
a-b= 8.5
a*b= 21.0
a/b= 5.25
a//b= 5.0
a%b= 0.5
a**b= 110.25
Example 3: test.py
10 / 2 # 5.0
10 // 2 # 5
10.0 / 2 # 5.0
10.0 // 2 # 5.0
Note: / operator always performs floating point arithmetic. Hence it will always
return float value.
But Floor division (//) can perform both floating point and integral arithmetic. If
arguments are int type then result is int type. If at least one argument is
float type then result is float type.
Note:
✓ We can use +, * operators for str type also.
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
✓ If we want to use + operator for str type then compulsory both
arguments should be str type only otherwise we will get error.
✓ + is String concatenation operator
✓ * is String multiplication operator
Example:
>>> "Madhu"+10 #TypeError: must be str, not int
>>> "Madhu"+"10"
'Madhu10'
If we use * operator for str type then compulsory one argument should be int
and other
argument should be str type.
>>>2*"Python"
>>>"Python"*2
>>>2.5*"durga" #TypeError: can't multiply sequence by non-int of type
'float'
>>>"durga"*"durga" #TypeError: can't multiply sequence by non-int of
type 'str'
Note: For any number x, x/0 and x%0 always raises "ZeroDivisionError"
Example:
>>>10/0
>>>10.0/0
Relational Operators:
>, >=, <, <=
Example:
a = 10
b = 20
print("a > b is ", a > b)
print("a >= b is ", a >= b)
print("a < b is ", a < b)
print("a <= b is ", a <= b)
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
We can apply relational operators for str types also
Example:
a = "madhu"
b = "madhuF"
print("a > b is ", a > b)
print("a >= b is ", a >= b)
print("a < b is ", a < b)
print("a <= b is ", a <= b)
Example:
print(True > True)
print(True >= True)
print(10 > True)
print(False > True)
print(10>'durga')
TypeError: '>' not supported between instances of 'int' and 'str'
Note: Chaining of relational operators is possible. In the chaining, if all
comparisons return True then only result is True. If at least one comparison
returns False then the result is False.
Example:
print(10 < 20)
print(10 < 20 < 30)
print(10 < 20 < 30 < 40)
print(10 < 20 < 30 < 40 > 50)
Equality Operators:
== , !=
We can apply these operators for any type even for incompatible types also
>>> 10 == 20
False
>>> 10 != 20
True
>>> 10 == True
False
>>> False == False
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
True
>>> "madhu" == "madhu"
True
>>> 10 == "madhu"
False
Note: Chaining concept is applicable for equality operators. If at least one
comparison returns False then the result is False. otherwise the result is True.
>>>10 == 20 == 30 == 40
False
>>>10 == 10 == 10 == 10
True
Logical Operators:
The logical operators are and, or, not. We can apply these operators for all
types.
For Boolean types behavior:
✓ and : If both arguments are True then only result is True
✓ or : If at least one argument is True then result is True
✓ not : Complement i.e. True is False and False is True
Example:
✓ True and False is False
✓ True or False is True
✓ not False is True
For Non-Boolean types behavior:
✓ 0 means False
✓ Non-zero means True
✓ Empty string is always treated as False
x and y:
✓ If x is evaluating to false return x otherwise return y
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
Example:
print(10 and 20) #20
print(0 and 20) #0
If first argument is zero then result is zero otherwise result is y
x or y:
✓ If x evaluates to True then result is x otherwise result is y
Example:
print(10 or 20) #10
print(0 or 20) #20
not x:
✓ If x is evaluating to False then result is True otherwise False
Example:
print(not 10) #False
print(not 0) #True
Example:
print("leela" and "leelasoft")
print("" and "leela")
print("leela" and "")
print("" or "leela")
print(not "")
print(not "leela")
Bitwise Operators:
✓ We can apply these operators bitwise.
✓ These operators are applicable only for int and Boolean types.
✓ By mistake if we are trying to apply for any other type then we will get
Error.
✓ The operators are &, |, ^, ~, <<, >>
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
& : If both bits are 1 then only result is 1 otherwise result is 0
| : If at least one bit is 1 then result is 1 otherwise result is 0
^ : If bits are different then only result is 1 otherwise result is 0
~ : bitwise complement operator 1 is 0 & 0 is 1
<< : Bitwise Left shift
>> : Bitwise Right Shift
Example:
print(4 & 5) #Valid
print(10.5 & 5.6)
#TypeError: unsupported operand type(s) for &: 'float' and 'float'
print(True & True) #Valid
Example:
print(4 & 5)
print(4 | 5)
print(4 ^ 5)
Bitwise complement operator (~):
✓ We have to apply complement for total bits.
Example:
print(~5) #-6
Note:
The most significant bit acts as sign bit. 0 value represents positive value whereas
1 represents negative value.
Positive numbers will be represented directly in the memory whereas negative
numbers will be
represented indirectly in 2's complement form.
Shift Operators:
<< Left shift operator:
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
✓ After shifting the empty cells, we have to fill with zero.
Example:
print(10<<2) #40
>> Right Shift operator:
✓ After shifting the empty cells, we have to fill with sign bit. (0 for positive
value and 1 for negative value).
Example:
print(10>>2) #2
We can apply bitwise operators for Boolean types also
Example:
print(True & False) # False
print(True | False) # True
print(True ^ False) # True
print(~True) # -2
print(True << 2) # 4
print(True >> 2) # 0
Assignment Operators:
We can use assignment operator to assign value to the variable.
Example:
x = 0
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
We can combine assignment operator with some other operator to form
compound assignment operator.
Example:
x += 10 is equals to x = x + 10
The following is the list of all possible compound assignment operators in Python
+=, -=, *=, /=, %=, //=, **=
&=, |=, ^=, >>=, <<=
Example:
x = 10
x += 20
print(x)
Example:
x = 10
x &= 5
print(x)
Ternary Operator:
Syntax:
x = firstValue if condition else secondValue
If condition is True then firstValue will be considered else secondValue
will be considered.
Example:
a, b = 10, 20
x = 30 if a < b else 40
print(x) #30
Example: Read two numbers from the keyboard and print minimum value
a = int(input("Enter First Number:"))
b = int(input("Enter Second Number:"))
min = a if a < b else b
print("Minimum Value:", min)
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
Output:
Enter First Number:10
Enter Second Number:30
Minimum Value: 10
Note: Nesting of ternary operator is possible.
Example: Program for minimum of 3 numbers
a = int(input("Enter First Number:"))
b = int(input("Enter Second Number:"))
c = int(input("Enter Third Number:"))
min = a if a < b and a < c else b if b < c else c
print("Minimum Value:", min)
Example: Program for maximum of 3 numbers
a = int(input("Enter First Number:"))
b = int(input("Enter Second Number:"))
c = int(input("Enter Third Number:"))
max = a if a > b and a > c else b if b > c else c
print("Maximum Value:", max)
Example:
a = int(input("Enter First Number:"))
b = int(input("Enter Second Number:"))
print("Both numbers are equal" if a == b else "First Number is Less than
Second Number" if a < b else "First Number Greater than Second Number")
Special operators:
Python defines the following 2 special operators
1. Identity Operators
2. Membership operators
1. Identity Operators
✓ We can use identity operators for address comparison.
✓ 2 identity operators are available. They are is, is not
✓ r1 is r2 returns True if both r1 and r2 are pointing to the same object
✓ r1 is not r2 returns True if both r1 and r2 are not pointing to the same
object
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
Example:
a = 10
b = 10
print(a is b) # True
x = True
y = True
print(x is y) # True
Example:
a="madhu"
b="madhu"
print(id(a))
print(id(b))
print(a is b)
Example:
list1 = ["one", "two", "three"]
list2 = ["one", "two", "three"]
print(id(list1))
print(id(list2))
print(list1 is list2) # False
print(list1 is not list2) # True
print(list1 == list2) # True
Note:
We can use ‘is’ operator for address comparison whereas ‘==’ operator for
content comparison.
2. Membership operators:
✓ We can use Membership operators to check whether the given object
present in the given collection. (It may be String, List, Set, Tuple or Dict).
✓ 2 membership operators are available. They are in, not in
✓ in Returns True if the given object presents in the specified Collection
✓ not in Returns True if the given object not present in the specified
Collection
Example:
x = "hello learning Python is very easy!!!"
print('h' in x) # True
print('d' in x) # False
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
print('d' not in x) # True
print('Python' in x) # True
Example:
list1 = ["sunny", "bunny", "chinny", "pinny"]
print("sunny" in list1) # True
print("tunny" in list1) # False
print("tunny" not in list1) # True
Operator Precedence and Associativity:
When different operators appear in the same expression, the normal rules of
arithmetic apply. All Python operators have a precedence and associativity:
✓ Precedence—when an expression contains two different kinds of
operators, which should be applied first?
✓ Associativity—when an expression contains two operators with the same
precedence, which should be applied first?
Example:
print(3 + 10 * 2) #23
print((3 + 10) * 2) #26
The following list describes operator precedence in Python
() Parenthesis
** exponential operator
~, - Bitwise complement operator, unary minus operator
*, /, %, // multiplication, division, modulo, floor division
+, - addition, subtraction
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
<<, >> Left and Right Shift
& bitwise And
^ Bitwise X-OR
| Bitwise OR
>, >=, <, <=, ==, != Relational or Comparison operators
=, +=, -=, *= Assignment operators
is, is not Identity Operators
in, not in Membership operators
not Logical not
and Logical and
or Logical or
Example:
a = 30
b = 20
c = 10
d = 5
print((a + b) * c / d) # 100.0
print((a + b) * (c / d)) # 100.0
print(a + (b * c) / d) # 70.0
Example:
print(3 / 2 * 4 + 3 + (10 / 5) ** 3 - 2)
print(3 / 2 * 4 + 3 + 2.0 ** 3 - 2)
print(3 / 2 * 4 + 3 + 8.0 - 2)
print(1.5 * 4 + 3 + 8.0 - 2)
print(6.0 + 3 + 8.0 - 2)
print(15.0)
Mathematical Functions (math Module)
A Module is collection of functions, variables and classes etc.
math is a module that contains several functions to perform mathematical
operations.
If we want to use any module in Python, first we have to import that module.
import math
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
Once we import a module then we can call any function of that module.
import math
print(math.sqrt(16))
print(math.pi)
4.0
3.141592653589793
We can create alias name by using as keyword.
import math as m
Once we create alias name, by using that we can access functions and variables of
that module
import math as m
print(m.sqrt(16))
print(m.pi)
We can import a particular member of a module explicitly as follows:
from math import sqrt
from math import sqrt, pi
If we import a member explicitly then it is not required to use module name while
accessing.
from math import sqrt, pi
print(sqrt(16))
print(pi)
print(math.pi) # NameError: name 'math' is not defined
important functions of math module:
ceil(x)
floor(x)
pow(x, y)
factorial(x)
trunc(x)
gcd(x, y)
sin(x)
cos(x)
tan(x)
www.leelasoft.com Cell: 78 42 66 47 66
Leela Soft Python Madhu B
important variables of math module:
pi 3.14
e 2.71
inf infinity
nan not a number
Write a Python program to find area of circle
pi*r**2
from math import pi
r = 16
print("Area of Circle is :", pi * r ** 2)
Output: Area of Circle is: 804.247719318987
www.leelasoft.com Cell: 78 42 66 47 66