0% found this document useful (0 votes)
11 views

Unit 2

Uploaded by

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

Unit 2

Uploaded by

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

UNIT 2

OPERATORS IN PYTHON

An operator is used to perform arithmetic, logical, assignment,comparison, existence operations


between two or multiple values.
Python supports below operators:
a. Arithmetic operators
b. Logical operators
c. Comparison/Relational operators
d. Bitwise operators
e. Shorthand operators
f. Identity operators
g. Membership operators

a. Arithmetic operators: The symbols used to perform arithmetic operations are: +,-,*,/,//,%,**
Below table shows the description of these operators.

Symbol Name of operator Purpose Example

+ Addition operator Add two or more numeric a=10;b=20


types c=a+b
print(c)
#output: 30

- Subtraction operator Subtracts two or more a=10;b=20


numeric types c=a-b
print(c)
#output: -10

* Multiplication operator multiplies two or more a=10;b=20


numeric types c=a*b
print(c)
#output: 200

/ Division operator Divides two numeric types a=5;b=2


and returns a real number c=a/b
print(c)
#output: 2.5

// Floor Division operator Divides two numeric types a=5;b=2


and returns quotient as c=a//b
integer print(c)
#output: 2
% Modulo operator Divides two numeric types a=5;b=2
and returns remainder as c=a%b
integer print(c)
#output: 1

** Exponent operator Returns exponent value for a=5;b=2


two values a,b i.e. returns a c=a**b
power b print(c)
#output: 25

B. Logical operators: These operators take conditional statements as an expression and return
True or False if the expression evaluates true or false. Symbols used are : and ,or , not

Below table shows the description of these operators.

Symbol Name of operator Purpose Example

and Logical ‘and’ operator Returns true if all the a=10;b=20,c=30


conditional statements in an c=(a<b) and (b>c)
expression are true else print(c)
returns false #output: False

or Logical ‘or’ operator Returns true if the any of the a=10;b=20,c=30


conditional statement in an c=(a<b) or (b>c)
expression is true else returns print(c)
false #output: True

not Logical ‘not’ operator It’s a unary operator that a=10;b=20,c=30


reverses the result, returns c=not (a<b)
False if the result is true in an print(c)
expression. Returns True if #output: False
the result is false in an
expression

C. Comparison/Relational operators
This type of operator is used to compare two values and returns True or False. The symbols used
are: > ,< , >=, <=, ==, !=

Symbol Name of operator Purpose Example

> Greater than Returns True if the first operand is a=10;b=20


greater than second else returns false. print(a>b)
#output: False
< Less than Returns True if the first operand is less a=10;b=20
than second else returns false. print(a<b)
#output:True

>= Greater than or Returns True if the first operand is a=10;b=20,c=10


equal to greater than or equal to the second else print(a>=b, a>=c)
returns false. #output: False, True

<= Less than or equal Returns True if the first operand is less a=10;b=20,c=10
to than or equal to the second else returns print(a<=b,a>=c)
false. #output: True,True

== Equality Returns True if the first operand is a=10;b=20


equal to the second else returns false. print(a==b)
#output: False

!= Not equality Returns True if the first operand is not a=10;b=20

equal to the second else returns false. print(a!=b)


#output: True

D. Bitwise operators
This type of operator is used to perform the operations on the given data at the bit-level. When a
number is given , these operators use its binary value (0’s and 1’s) to perform arithmetic
computation and return the result. The symbols used are: &, |, ^, << , >>, ~

Symbol Name of operator Purpose Example

& Bitwise and Sets each bit to 1 if both bits are 1 else a=5;b=4
sets to 0 in the given operands in bit print(a&b)
level #output: 4

| Bitwise or Sets each bit to 1 if any of the bits are a=5;b=4


1 else sets to 0 in the given operands print(a|b)
in bit level #output: 5

^ Bitwise xor Sets each bit to 1 if only one of the bits a=5;b=4
is 1 else sets to 0 in the given operands print(a^b)
in bit level #output: 1

<< Bitwise left-shift Each bit in the first operand Shifts left a=5;b=4
by pushing zeros in from the right and print(a<<b)
the leftmost bits will be discarded. #output: 80
This shifting will be repeated upto
second operand times.
>> Bitwise right-shift Each bit in the first operand Shifts a=60;b=4
right by pushing zeros in from the left print(a>>b)
and the rightmost bits will be #output: 3
discarded. This shifting will be
repeated upto second operand times.

~ Bitwise NOT It is a unary operator that inverts all a=60


the bits in the operand from 0’s to 1’1 print(~a)
and 1’s to 0’s #output: -61

E. Shorthand /Assignment operators:


These operators are used to assign values to variables. The symbols used are: +=, -=,
*=,/=,//=,**=,%=,&=,|=,^=,>>=,<<=. These operators are also called compound operators.

Symbol Example Same as

+= a=3;b=4 a=3;b=4
a+=b a=a+b
print(a) print(a)
#output:7 #output:7

-= a=3;b=4 a=3;b=4
a-=b a=a-b
print(a) print(a)
#output:-1 #output:-1

*= a=3;b=4 a=3;b=4
a*=b a=a*b
print(a) print(a)
#output:12 #output:12

/= a=3;b=4 a=3;b=4
a/=b a=a/b
print(a) print(a)
#output:0.75 #output:0.7
5

//= a=3;b=4 a=3;b=4


a//=b a=a//b
print(a) print(a)
#output:0 #output:0

%= a=3;b=4 a=3;b=4
a%=b a=a%b
print(a) print(a)
#output:3 #output:3
**= a=3;b=4 a=3;b=4
a**=b a=a**b
print(a) print(a)
#output:81 #output:81

&= a=3;b=4 a=3;b=4


a&=b a=a&b
print(a) print(a)
#output:0 #output:0

|= a=3;b=4 a=3;b=4
a|=b a=a|b
print(a) print(a)
#output:7 #output:7

^= a=3;b=4 a=3;b=4

a^=b a=a^b
print(a) print(a)
#output:7 #output:7

<<= a=3;b=4 a=3;b=4


a<<=b a=a<<b
print(a) print(a)
#output:48 #output:48

>>= a=3;b=4 a=3;b=4


a>>=b a=a>>b
print(a) print(a)
#output:0 #output:0

F. Identity operators:
These operators are used to compare two objects and check if both objects are referring to
the same memory location or not. Two keywords are used for comparing objects: is and is not

Keyword Purpose Example

is Returns true if two objects are same and a=10; b=a;


referring to same memory location print( b is a)
#output: True

is not Returns true if two objects are not same and a=10; b=a;c=20
not referring to same memory location print(c is not a)
print( b is not a)
#output: True False
G. Membership operators
These operators are used to check for the existence of a value in a given sequence of data.
Two keywords are used for comparing objects: in and not in

Keyword Purpose Example

in Returns true if a value is existed in a given a=[1,2,3,4,5];


sequence of data print( 10 in a)
#output: False

not in Returns true if a value is not existed in a a=[1,2,3,4,5]


given sequence of data print(10 not in a)
#output: True

OPERATOR PRECEDENCE
In python, we follow a special rule named as PEMDAS rule to specify the order of evaluating a
given arithmetic expression.
If an expression contains arithmetic operators then as per PEMDAS rule those operators will be
evaluated first.
PEMDAS stands for Parenthesis (), Exponent (**), Multiplication (*) and Division(/, //) ,
Addition(+) and Subtraction(-)
As per the above rule, first priority is given to (), second priority is for Exponent operator(**),
third priority is for *,/,// and fourth priority is for +,-.
As *,/,// and +,- are having equal precedence, the given expression gets evaluated from left to
right occurrence of the operator.

Example-1: Step-1 : 3**2=9 => 15+5-9*3//4+3%6


Step-2: 9*3 ⇒15+5-27//4+3%6
print(15+5-3**2*3//4+3%6) Step-3: 27//4 ⇒ 15+5-6+3%6
Output: 17 Step-4: 3%6 ⇒15+5-6+3
Step-5: 15+5 ⇒ 20-6+3
Step-6: 20-6 ⇒14+3
Step-7: 14+3 ⇒17
Example-2: Step-1: (5-3) ⇒ (2) ⇒ 15+2**2*3//4+(3%6)
print(15+(5-3)**2*3//4+(3%6)) Step-2: (3%6) ⇒(3) ⇒ 15+2**2*3//4+3
Output: 21 Step-3: 2**2 ⇒4⇒15+4*3//4+3
Step-4: 4*3⇒12⇒15+12//4+3
Step-5: 12//4⇒3⇒15+3+3
Step-6: 15+3⇒18⇒18+3
Step-7: 18+3⇒21
Below table lists the precedence for all operators from higher precedence to lowest.

Operator Description

** Exponentiation

~,+,- Complement, unary plus, unary minus

*,/,//,% Multiply,divide,floor division, modulo division

+,- addition,subtraction

>>,<< Left shift,right shift

& Bitwise and

^,| Bitwise xor, bitwise OR

<,>,<=,>= Comparison operators

==,!= Equality operators

=,+=,-=,*=,/=,//=,**= Assignment operators

is, is not Identity operators

In ,not in Membership operators

and,or,not Logical operators

SOME BUILT-IN FUNCTIONS


1. len() : This method finds the length of a string, list,set,tuple and dictionary.
Example:
s1="python program" Output:
print(len(s1)) 14
li=[1,2,3,4,5] 5
print(len(li)) 5
t1=(1,2,3,4,5) 3
print(len(t1)) 3
s1={1,2.3,'sample',True}
print(len(s1))
d1={'x':1,'y':2,'z':3}
print(len(s1))

2. id() : This method prints address of an object


Example:
3. chr() : This method returns the character associated with the given ASCII value.
Example:

4. ord(): This method returns the ASCII value of a given character


Example:

5. type(): This method is used to specify the data type of a given variable or a value.

6. eval() : This method is used to evaluate the given arithmetic expression. Expression will
be given as a string.
Example:

7. exec(): This function is used to execute the set of statements given as a string.
Example:

8. hex(): This function is used to return the hexadecimal value of a given number.
Example:

9. oct(): This function is used to return the octal value of a given number.
Example:

10. bin(): This function is used to return the binary value of a given number.
Example:

11. max(): This function returns the maximum value among the list of numbers.
Example:
12. min(): This function returns the minimum value among the list of numbers.
Example:

13. pow(a,b): This function returns the exponent value given numbers a,b. Returns a power
b.
Example:

14. sum(list): returns the sum of list of numbers


Example:

15. dir(): display the list of variables, functions of the given object.
Example: Displaying the list of methods and variables in a tuple

CONDITIONAL STATEMENTS
These statements are also called Control Statements which are crucial for any programming
language.
Control statements are used to control the flow of execution in a program.
They are used to perform some tasks like:
i) executing statements through decision making
ii) executing statements repeatedly more than once
iii) skipping statements and jump to other statements
In python, conditional statements are classified into three:
a. Selection statements
b. Iteration statements
c. Jump statements
Without these ,the program should perform sequential execution upto nth statement.

a. Selection statements :These statements are used to perform decision making. An


expression will be given, if it evaluates to true, a certain sequence of statements will be
executed, otherwise other set of statements will be executed but not both.
Below are types of selection statements.

I. simple if statement: A keyword “if” is used to give an expression. If expression


evaluates to true, statements inside if block will be executed otherwise skipped and
control will be placed after “if”. Below is the syntax.
Syntax:
Stmt before if
if expression :
Stmt-2
Stmt-3

stmt-N
Stmt after if

Example-1 Output:
a=10 before if
print(“before if”) after if block
If a>20:
print(“inside if block”)
print(“a is greater than 20”)
print(“after if block”)

Example-2 Output:
a=100 before if
print(“before if”) inside if block
If a>20: a is greater than 20
print(“inside if block”) after if block
print(“a is greater than 20”)
print(“after if block”)

II. if-else statement: A keyword “if” is used to give an expression. If expression


evaluates to true, statements inside if block will be executed otherwise statements inside
else block will be executed. Either if block or else block will be executed depending on
the expression evaluation but not both. Here ‘else’ is also a keyword.
Syntax:
Stmts before if
if expression :
Stmt-1
Stmt-2

stmt-N
else :
Stmt-1
Stmt-2

Stmt-N
Stmt after else
Note: Indentation is important to specify the block of statements in if-else. If and else
statement ends with a colon (:)
Example-1 Output:
a=10; b=20 before if
print(“before if”) inside else block
If a>b: a<b
print(“inside if block”) after if-else block
print(“a > b”)
else:
print(“inside else block”)
print(“a < b”)
print(“after if-else block”)

Example-2 Output:
a=100 before if
print(“before if”) inside if block
If a>20: a>b
print(“inside if block”) after if-else block
print(“a is greater than 20”)
print(“after if block”)

III)if-elif-else statements: It is a multi-decision statement in which multiple expressionsare


given.But only one expression will be evaluated to true such that corresponding statements
under that expression will be executed. Other statements are skipped which are evaluated to
false.
If no expression is evaluated to true, the else block will be executed.
3 keywords are used: if, elif and else. All these keywords must have the same indentation.
Below is the syntax:
Syntax: Flowchart:
if expr-1:
Stmt-1
elif expr-2:
Stmt-2
elif expr-3:
Stmt-3

elif expr-n:
Stmt-n
else:
Stmt(s) inside else

Example: Output:
a=56 between 50 and 100
if a>0 and a<20:
print(“ between 0 and 20”)
elif a>20 and a<50:
print(“between 20 and 50”)
elif a>50 and a<100:
print(“between 50 and 100”)
else:
print(“ value > 100”)
d. Nested if-else statements: An if statement inside another if statement or else
statement or if-else statement inside another if statement or else statement.
Syntax-1: Flowchart-1
if expr-1:
if expr-2:
Stmt-1
else:
if expr-3:
stmt-2

Syntax-2: Flowchart-2
if expr-1:
if expr-2:
Stmt-1
else:
Stmt-2
else:
if expr-3:
Stmt-3
else:
stmt-4

Example: Output:
iv) Iteration statements: These statements are used to execute a certain set of statements
repeatedly till a given condition is satisfied. To perform an iteration statements, 3 thingsto be
considered:
i. Variable initialization
ii. Iteration condition
iii. Variable updation
Once a variable has been initialized, it will be used for checking an iteration condition. If
the condition is true,then statements inside the condition block will be executed and the iteration
variable should be updated. The control repeats the iteration condition again for evaluating true
or false. This process repeats until the condition becomes false.
During the iteration process, condition, statements inside condition and variable updation will be
executed many times but variable initialization will happen only once. Observe the below
flowchart.

Two keywords are used for iteration statements: while and for statements.
I. While statement: It is called a pre-test iteration statement as the condition is evaluated at
the beginning of an iteration. While statements never execute at all if the condition fails.

Syntax-1: counter based loop Syntax-2: Event based loop


Variable initialization Variable initialization
While condition: While True:
statement(s) statement(s)
Variable updation Sentinel code to break while
Statement after while Statement after while
Two types of while loops can be defined. Counter based loop and event based loop.

Counter based loop → loop runs with a finite condition and a counter variable is
updated always inside the loop to reach the finite condition. User knows how many times
the loop runs.

Event based loop→ loop runs with infinite condition. User doesn't know how many
times the loop runs. To stop this loop, a special if statement code called sentinel code
should be used in the loop to stop the loop unconditionally.

Example-1 : counter based loop Output-1

Example-2 : Event based loop Output-2

Note: In this example,if-else condition is


the sentinel code

II. for statement:


“for” loop syntax uses a sequence of values as a condition and a loop variable is
initialized to the first value of the sequence. For every iteration of loop, the loop variable
reinitialized to the next value of a sequence and verify the value belongs to the sequence.
The loop continues until the loop variable is initialized to the last sequence number.
range() function: it is a built-in function used to generate the sequence of numbers
between first and second parameters in it.
Syntax:
range(a,b) → will generate a sequence of numbers from a to b-1.
Example:
range(5,10) → generates numbers from 5 to 9.
Syntax of ‘for’ loop:
for variable in sequence:
statement(s)
Here the sequence means either a range() function or sequence data type.
Flow of statements in for loop:

Example-1: using range() function as Output-1


sequence

Example-2: using list as sequence Output-2


v) Jump statements: These statements are used to
i. skip statements in a loop and terminate loop
ii. Skip statements in current iteration and repeat for next iteration
iii. Provide an empty definition body for iteration statements, functions and classes.
Three keywords are used in jump statements. They are : break, continue and pass
I. Break: this keyword is used to skip the statements after ‘break’ in the current iteration of
the loop and terminate the loop.
→ it is used as a sentinel code for event based loops.
→ It cannot be used in outside loops

Syntax Example Output

while condition-1: a=1 12345


statement(s)-1 while a<10:
if condition-2 : print(a)
break if a==5:
statement(s)-2 break
statement(s) after while a=a+1
print(‘after while’)

II. Continue : this keyword is used to skip the statements after ‘continue’ in the current
iteration of the loop and repeat the next iteration of the loop.
→ it is used as a sentinel code for event based loops.
→ It cannot be used in outside loops

Syntax Example Output

while condition-1: a=1 13579


statement(s)-1 while a<10:
if condition-2 : if a%2==0:
continue a=a+1
statement(s)-2 continue
statement(s) after while print(a,end=" ")
a=a+1
print('after continue')
III. Pass statement: It is a keyword used to declare
A. any loop as empty loop
B. Any function as am empty body function
C. Any class is an empty body class.
‘Pass’ has no specific role except to declare empty definitions for loops, functions and
classes.
If a for loop has nothing to do, then declare it as ‘pass’.
If a function or class has no logic, then declare it as ‘pass’
Note: we cannot write empty body directly without ‘pass’
Example:

Example-1 Example-2 Example-3:


#empty for loop #empty function #empty class
for k in range(2,5): def func1(): class demo:
pass pass pass

FEW MORE THINGS IN VARIABLE ASSIGNMENT


1. Packing values to a variable
We can assign a group of values to a single variable. This is called list or set or tuple or
dictionary. Individual value can be accessed using index value range from 0 to size-1
where size means number of values.
Example:
a=[5,6,7,8]
2. Multiple assignments
We can assign multiple variables to multiple values at a time using the assignment
operator.
Example:
a,b,c=4,5,6 # assigns a=4,b=5,c=6
print(a,b,c) #output: 4 5 6
3. Unpacking values from a variable
We can assign a list of values to individual variables and access them using those
variables.
*a,b,c=litst1 → *a will be a list variable to store leftover elements in list1
after b and care initialized.

You might also like