Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
131 views

Operators in Python

This document discusses different types of operators in Python including arithmetic, comparison, assignment, logical, bitwise, and membership operators. Arithmetic operators perform mathematical calculations like addition and multiplication. Comparison operators compare values and return True or False. Assignment operators assign values to variables. Logical operators combine conditional statements. The document provides examples of using each type of operator and explains their functionality in Python.

Uploaded by

Rahul V
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
131 views

Operators in Python

This document discusses different types of operators in Python including arithmetic, comparison, assignment, logical, bitwise, and membership operators. Arithmetic operators perform mathematical calculations like addition and multiplication. Comparison operators compare values and return True or False. Assignment operators assign values to variables. Logical operators combine conditional statements. The document provides examples of using each type of operator and explains their functionality in Python.

Uploaded by

Rahul V
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Python Programming Operators CMP Infotech

Operator
Contents
Operator .................................................................................................................................................... 1
Types of Operator ..................................................................................................................................... 1
Arithmetic Operators ................................................................................................................................ 1
Comparison Operators .............................................................................................................................. 3
Assignment Operators ............................................................................................................................... 4
Logical Operators...................................................................................................................................... 5
Bitwise Operators...................................................................................................................................... 7
Membership Operators.............................................................................................................................. 7
Identity Operators ..................................................................................................................................... 9
Operators Precedence.............................................................................................................................. 10

Operators are the constructs which can manipulate the value of operands.

Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Types of Operator
Python language supports the following types of operators.

 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Arithmetic Operators

CMPINFOTECH pg. 1
Python Programming Operators CMP Infotech

Arithmetic Operators perform various arithmetic calculations like addition,


subtraction, multiplication, division, %modulus, exponent, etc. There are various
methods for arithmetic calculation in Python like you can use the eval function,
declare variable & calculate, or call functions.

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


Adds values on either side of the
+ Addition a + b = 30
operator.
Subtracts right hand operand from left
- Subtraction a – b = -10
hand operand.
* Multiplies values on either side of the
a * b = 200
Multiplication operator
Divides left hand operand by right hand
/ Division b/a=2
operand
Divides left hand operand by right hand
% Modulus b%a=0
operand and returns remainder
Performs exponential (power)
** Exponent a**b =10 to the power 20
calculation on operators
Floor Division - The division of
operands where the result is the
quotient in which the digits after the
9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -
// decimal point are removed. But if one
11.0//3 = -4.0
of the operands is negative, the result is
floored, i.e., rounded away from zero
(towards negative infinity):

Example: For arithmetic operators we will take simple example of addition where
we will add two-digit 4+5=9

CMPINFOTECH pg. 2
Python Programming Operators CMP Infotech

x= 4
y= 5
print x + y

The output of this code is "9."

Similarly, you can use other arithmetic operators like for multiplication(*),
division (/), substraction (-), etc.

Comparison Operators
These operators compare the values on either sides of them and decide the relation among them.
They are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


If the values of two operands are equal,
== (a == b) is not true.
then the condition becomes true.
If values of two operands are not equal,
!=
then condition becomes true.
If the value of left operand is greater than
> the value of right operand, then condition (a > b) is not true.
becomes true.
If the value of left operand is less than the
< value of right operand, then condition (a < b) is true.
becomes true.

CMPINFOTECH pg. 3
Python Programming Operators CMP Infotech

If the value of left operand is greater than


>= or equal to the value of right operand, (a >= b) is not true.
then condition becomes true.
If the value of left operand is less than or
<= equal to the value of right operand, then (a <= b) is true.
condition becomes true.

Example: For comparison operators we will compare the value of x to the value of
y and print the result in true or false. Here in example, our value of x = 4 which is
smaller than y = 5, so when we print the value as x>y, it actually compares the
value of x to y and since it is not correct, it returns false.
x = 4
y = 5
print('x > y is',x>y)

The output of this code will be ('x > y is', False)

Likewise, you can try other comparison operators (x < y, x==y, x!=y, etc.)

Assignment Operators
Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


= Assigns values from right side operands c = a + b assigns value of a + b into c
to left side operand
+= Add It adds right operand to the left operand c += a is equivalent to c = c + a
AND and assign the result to left operand
-= It subtracts right operand from the left c -= a is equivalent to c = c - a
Subtract operand and assign the result to left
AND operand
*= It multiplies right operand with the left c *= a is equivalent to c = c * a
Multiply operand and assign the result to left
AND operand
/= Divide It divides left operand with the right c /= a is equivalent to c = c / ac /= a is
AND operand and assign the result to left equivalent to c = c / a
operand

CMPINFOTECH pg. 4
Python Programming Operators CMP Infotech

%= It takes modulus using two operands c %= a is equivalent to c = c % a


Modulus and assign the result to left operand
AND
**= Performs exponential (power) c **= a is equivalent to c = c ** a
Exponent calculation on operators and assign
AND value to the left operand
//= Floor It performs floor division on operators c //= a is equivalent to c = c // a
Division and assign value to the left operand

Example: Python assignment operators is simply to assign the value, for example
num1 = 4
num2 = 5
print ("Line 1 - Value of num1 : ", num1)
print ("Line 2 - Value of num2 : ", num2)

The output of this code will be

('Line 1 - Value of num1 : ', 4)

('Line 2 - Value of num2 : ', 5)

Example of compound assignment operator

We can also use a compound assignment operator, where you can add, subtract,
multiply right operand to left and assign addition (or any other arithmetic function)
to the left operand.

 Step 1: Assign value to num1 and num2


 Step 2: Add value of num1 and num2 (4+5=9)
 Step 3: To this result add num1 to the output of Step 2 ( 9+4)
 Step 4: It will print the final result as 13

num1 = 4
num2 = 5
res = num1 + num2
res += num1
print ("Line 1 - Result of + is ", res)

The output of this code will be

('Line 1 - Result of + is ', 13)

Logical Operators

CMPINFOTECH pg. 5
Python Programming Operators CMP Infotech

Operator Description Example

and Logical If both the operands are true then condition becomes (a and b)
AND true. is true.

or Logical OR If any of the two operands are non-zero then (a or b)


condition becomes true. is true.

not Logical Used to reverse the logical state of its operand. not(a
NOT and b) is
false.

Logical operators in Python are used for conditional statements are true or false.
Logical operators in Python are AND, OR and NOT. For logical operators
following condition are applied.

 For AND operator – It returns TRUE if both the operands (right side and left side) are
true
 For OR operator- It returns FALSE if either of the operand (right side or left side) is true
 For NOT operator- returns TRUE if operand is false

Example: Here in example we get true or false based on the value of a and b
a = True
b = False
print('a and b is',a and b)
print('a or b is',a or b)
print('not a is',not a)

The output of this code will be

('a and b is', False)

('a or b is', True)

('not a is', False)

CMPINFOTECH pg. 6
Python Programming Operators CMP Infotech

Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13;
Now in binary format they will be as follows −

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

There are following Bitwise operators supported by Python language

Operator Description Example


& Binary Operator copies a bit to the result if it (a & b) (means 0000 1100)
AND exists in both operands
| Binary OR It copies a bit if it exists in either (a | b) = 61 (means 0011 1101)
operand.
^ Binary It copies the bit if it is set in one (a ^ b) = 49 (means 0011 0001)
XOR operand but not both.
~ Binary It is unary and has the effect of (~a ) = -61 (means 1100 0011 in 2's
Ones 'flipping' bits. complement form due to a signed
Complement binary number.
<< Binary The left operands value is moved left a << = 240 (means 1111 0000)
Left Shift by the number of bits specified by the
right operand.
>> Binary The left operands value is moved right a >> = 15 (means 0000 1111)
Right Shift by the number of bits specified by the
right operand.

Membership Operators
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below

CMPINFOTECH pg. 7
Python Programming Operators CMP Infotech

Operator Description Example


Evaluates to true if it finds a variable in
x in y, here in results in a 1 if x is a
In the specified sequence and false
member of sequence y.
otherwise.
Evaluates to true if it does not finds a
x not in y, here not in results in a 1 if x is
not in variable in the specified sequence and
not a member of sequence y.
false otherwise.

Example: For example here we check whether the value of x=4 and value of y=8
is available in list or not, by using in and not in operators.
x = 4
y = 8
list = [1, 2, 3, 4, 5 ];

if ( x in list ):
print "Line 1 - x is available in the given list"
else:
print "Line 1 - x is not available in the given list"

if ( y not in list ):
print "Line 2 - y is not available in the given list"
else:
print "Line 2 - y is available in the given list"

The output of this code is

Line 1 - x is available in the given list

Line 2 - y is not available in the given list

 Declare the value for x and y


 Declare the value of list
 Use the "in" operator in code with if statement to check the value of x existing in the list
and print the result accordingly
 Use the "not in" operator in code with if statement to check the value of y exist in the
list and print the result accordingly
 Run the code- When the code run it gives the desired output

CMPINFOTECH pg. 8
Python Programming Operators CMP Infotech

Identity Operators

 Identity operators compare the memory locations of two objects. There are two Identity
operators explained below:

Operator Description Example


Evaluates to true if the variables on
x is y, here is results in 1 if id(x) equals
Is either side of the operator point to the
id(y).
same object and false otherwise.
Evaluates to false if the variables on
x is not y, here is not results in 1 if id(x) is
is not either side of the operator point to the
not equal to id(y).
same object and true otherwise.

 Operator is: It returns true if two variables point the same object and false otherwise
 Operator is not: It returns false if two variables point the same object and true
otherwise

Example:
x = 20
y = 20

if ( x is y ):

print "x & y SAME identity"

y=30

if ( x is not y ):

print "x & y have DIFFERENT identity"

The output of this code will be

x & y SAME identity

x & y have DIFFERENT identity

 Declare the value for variable x and y


 Use the operator "is" in code to check if value of x is same as y
 Next we use the operator "is not" in code if value of x is not same as y
 Run the code- The output of the result is as expected

CMPINFOTECH pg. 9
Python Programming Operators CMP Infotech

Operators Precedence

 The following table lists all operators from highest precedence to lowest.

Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus (method names for the last two
are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= Assignment operators
**=
is is not Identity operators
in not in Membership operators
not or and Logical operators

Example:
v = 4
w = 5
x = 8
y = 2
z = 0
z = (v+w) * x / y;
print "Value of (v+w) * x/ y is ", z

The output of this result is

Value of (v+w) * x/ y is 36

 Declare the value of variable v,w…z


 Now apply the formula and run the code
 The code will execute and calculate the variable with higher precedence and will give
the output

CMPINFOTECH pg. 10
Python Programming Operators CMP Infotech

Summary:
Operators in a programming language are used to perform various operations on
values and variables. In Python, you can use operators like

 There are various methods for arithmetic calculation in Python as you can use the eval
function, declare variable & calculate, or call functions
 Comparison operators often referred as relational operators are used to compare the
values on either side of them and determine the relation between them
 Python assignment operators are simply to assign the value to variable
 Python also allows you to use a compound assignment operator, in a complicated
arithmetic calculation, where you can assign the result of one operand to the other
 For AND operator – It returns TRUE if both the operands (right side and left side) are
true
 For OR operator- It returns FALSE if either of the operand (right side or left side) is true
 For NOT operator- returns TRUE if operand is false
 There are two membership operators that are used in Python. (in, not in).
 It gives the result based on the variable present in specified sequence or string
 The two identify operators used in Python are (is, is not)
 It returns true if two variables point the same object and false otherwise
 Precedence operator can be useful when you have to set priority for which calculation
need to be done first in a complex calculation.

CMPINFOTECH pg. 11

You might also like