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

Unit 2 Notes Python Operators and Control Flow Statements Part 1

The document discusses various Python operators and control flow statements. It describes operator types like arithmetic, comparison, assignment, logical, and bitwise operators. It provides examples of using each operator type and how they work. Control flow statements allow programmers to control the flow of execution of code based on conditions.

Uploaded by

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

Unit 2 Notes Python Operators and Control Flow Statements Part 1

The document discusses various Python operators and control flow statements. It describes operator types like arithmetic, comparison, assignment, logical, and bitwise operators. It provides examples of using each operator type and how they work. Control flow statements allow programmers to control the flow of execution of code based on conditions.

Uploaded by

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

Chapter -2

Unit- J I
Python OperatorS an d
Control Flow StatementS.
-10 MarkS
2-1 Basic Op erator S
- An operator is Sinqle Or Set_af specia Sumbols
that pertormS pre-defined eperations on apeiators
Puthon hasa
arich Set o f operatorS which
aie divided into fallowing Seven
gaupsi
1,Arithmetic operataS
R Comparison/ Relationql aperatorS
3ASsignment Qperatarg
4 Loqical 0peratorS
5 Bitwise OperatarS
6, Membershu p Operators
7 Tdentity Operqtors
ArithmetiC Operat or
Arith metic OperatarS aie to per for m
arithmetic operationS on two operands.
Operator Name Deseri ption
addition performS addition of two operands
Subtra ction Perfor ms Subtrcaction cf opG two

multiplication PesformS multiplication of tuo.


aperao ds
float Div ision performS float division of two
O perands.
Moor Division per for mS flooT divisi on of two
Operandls and returns integer
Tslt
modulus obtouns Remaunder

Operator Eaample
+ +y
*

*Proqram that demons trat e S al above


orithmetic OperatorS,
a 15
b 4
add a +b
Sub a-b
Mul a*b
lootoiv= a/ b
Ploor div = a// b
mod a 7. b
print("
"Addition is ", add)
print (" Subtraction is " , Sub)
print ( Multiplication is:", mul)
print Float Division is ", floatdiv)
print Hoo DivISion is floor div)
print( Remainder is ", mod)

Output
Additi on is:19
Subtraction is 11
Multiplication is 60
float Division is: 3.75
Floor Di vision is 3
Remaander is:3

2 CompariSon Relationa CperatorS-


Relational OperatorS ae ta test the conditions
The 1elation a operatcrS 1eSults as Boolean
Tue or False.

OperotoI Name Desciption Example


geater than Results True, i t value of 7Y
left oper and is qreate r
than value of ight
operCund; otherwise
SwtS Palge

ess than ReswltS True, if value ot Ieft x<u


operand is less than value
ct ight operand oherwise
1eSulES false
Operato Name Descri p i o n Exomple
72 qreater than or ReswtS True, if value
af left operand s greater
e.qual to
than or equal to the value

Of right operan d; atherwise


1esul t.S false

< = l e s s than Or ResultS Trueif value


of left aperan d is less
y
equal to
than equal to the
o1

Value af Tight Operond


Other ige 1eSults fcle

_equalS t o Results rue, if values


Of both operan ds are
equalj otheruoise resultS

false

ResltS True, if values


not equal to
are
o f both operands
unequal, otherwise reswls
Palse

that demonStrateS all above


above
Program
1elotiona operato1S
E13
b 31
print ("IS a>b 2:",a>b)
print (1s axb?" ab)
printIS a=b? :",azb)
print I S a=b 2:, a lb)
print ("IS a>:b2:", az-b)
print (" 13 o:b2 :" a< -b)
Output:
1S a b ? false
1S a<b2:True
IS a:b?: false
IS ale b? True
IS ab2 Fals e
1S a : b 2 :Ttue

3Assignment perator
-The agsignment operator IS to assiqn
of 1ight operand o
the value /1eS ul t
exp1ession to the vari able /1efe1enee on
left The assignment opesator is
single
equals-to- Bign
Des cription Ezarnple
perator Name

value / 10
assiqn ment AsignS
Resut of right OR
operand nariable z=10+20
Cpresson to the

variable an ePt side.

ASS1gnment operatoris also helpful in


to perfovm
CYeatinq Short- hand expresionse
and assigninq 1eSult at the Same
operation
time.

Operotor Name Desciption Example shoitt


ot

+ add AND Add 7ight 9ide operand at=b a-a+b


with leftSide oper and
Subtracct AND 9ub tract nght operand a--b a:a-b
from eft
opeand and
then aSSign to left operand
mial tiply AND Multiply Tight operan d ab a-a*b
wth TePt operand and
then
assign to ert Operan d

/= division AND Per-forms floot division of a/-b a@/b


left operand with niqht
operand and then assign
toleft operand.
OperatoT Nama De scripti on le 9hortcut of

// : floor division PerformS floor allb a aIlb


AND division of teft
operand with right
operand and then
assiqn to left operand

Modulug AND Takes modulus usinq a b aa b


left and ight 0perandg
and a9siqn esult to
eft operand

b a=a>>b
Eaponent AND Calcul ote ezpon ent
Naue uSing operá'ndsS
and assi qn value to
teft oper and

Ezample
la b,c,d,e,f.g,hi,i k,A,m,na,2,3,45,7

8,9 10, I , 12, 13, 14


atb

e= f
9/ h

m**h
print(at :b resuts a.s "a)
print CC - d esultS a s ' c)
print ( e * f reswtS as:", e)
print(q/=h 1esul ts aS", 9)
pint i = j 1esults a9:",i)
print (" K%: eswts as: R
print ( m ** =n resultS aS ", m)

Outpu
atb 1ests as3
C- d vesultSs aS -

e*tTesults as 30
g / - h YesultS as o.875
II 1eSultS a s 0
1esult9 as I
m * =n resulls as : 3937376385 61928

4Logical Operators
Lagica operotorS re to test multiple

conditions. The logico OperatoTS CL


Tesultsas Boolean True or False .

Opeiafo Name Description Erample


and Logical AND Results True, if both opoan azb an
ConditionS a e True: other wise a c
TOSultS false
ar
Logical OR Results True, if both operand azb
Or
or conditiong ae TTue o therwise a7 C
yesults falsa.
NOT InvertS /TeverSes the Boolean not azh
Logical
not yesutS.
ample.
print ue and false, True and Folse)
pint ue o false", True or false)
printC True and True and True
True and Ti ue and Tue)
print (" True Y True or True Jrue or True
Or Tue)
printnot True:", not True
pint " not fal se:", not False)
Cutput
Tue and Falsee: Fals e
True or falge Tiue
TTue and TTue an d True True
Tue or TTue Tiue
not True false
not FadSe: True
pevate Hame Dea plon ampC

Ritwise AND Reult bit , fboth a&b


evandhits are 1
otherise esultS Dit

twse OR Resulls hit 1. if any alb


of the operand bit 1s L.
ather w ise 1eSult bit O.

A Sitwsc XOR ResultS bit 1if any a Ab

of the operand bit is 1


but nat both otherwise
eSultS bit o

i t wise NOT Invert individu al bitS

Left Shift The left oporand's value is a<cb


moved taward9 left by
the number of bit3 9pecified
by the ight aperanq

Riht Shift The lef t operand'S val ue 1S azzb


moved towardd tight by
the number of bits specified

by the ght operand.


Example
Progrom For Bitwise OperatorS -_

b ll1o001|
print a b esultS as a &b)
print(alb1eSultS a s , alb)
print("anb YesultS aS " a ^b)

print (" a 1eSultS aS:"", a )


print(" ak<2 resultS a s , a A)
Aint (b222 re5ul tS a9 " b222)

Output
a 8 b regultS as 8913 250
albe eSultS as12 297871
a Ab_nesultS a9: 3374621
a a esultS ag -lojoLLL
resultS aS 404 O 4 44 6
ai<
a>z2 YeSultS aS; 2775002

6Membership operato1S: -

-Pythan'S memberghip operator is ta check


an element/value/ obie ct in
the pesen.ceot
Specified equence ( LiSt or 1uple
or
gtring).
Pythonprovides two memb ership operators.
operotor Description

specifie d left operan d element ic


Resul t3 True,if
opesan d de quence
present in Speci fied right
otheruise resultS false.
left operand element is
hot in Results True, if Specifre d
not present in Speci fied ight operand Sequence
ohewise reswts falsej
fxomple
Python Program Por membershi p O perat arS
st L 10,4O 20.555, "Ravi 10o1

tuple 1(15,25,35.555,Jainee", a00)


Stringi Python is a gmart languaqe.'"
U
print (Presen ce of 1o in hst 1 1S:, 1a inlist1)

PIDt(presence of 25 in inlist 1)
listl is , 25
is: 1a intuple 1)
pTint ( presence of 10 in tuple
25 in tuplel1
print("presence of 25 in tuple 1 is:
is ", P in stuing1)
prnt" presence of P in Strinq1

0 ut put
Presence of l o in l i s t 1 is True
PreSence of 25 in LiSt 1 iS: folse
1 is false
Presence of LO in tuple
Presence of 2S in tuple t is : True
p1esen Ce Ot P in String 1 is: True

7 Tdentity aperators:
Python dentity aperatorS a e to compaie

twaseferenceS whether they pointsreferS


locati on S,. here ae
t o Same memoy
two lolenti tyOperatarS
10 Pythan

Oper oto Description


references /variables
if both operan d
ResultS True,
otherwise Resudts
points to Same memony location;
False.
referenees/variables
iF both operand
is not Results Tue,
to same memon location,'
do not pointS
aherwiSe
Tes tu tS Falge
Enam ple
a-5

b 5

pint( Does a andb point to Same mem or


ocatianS9"_ a is b)
print ("Does a and c poinS to Samememon
locaions2"a is C)
print Does a and b_nat pontS to Same
memo Locatton g 2 a is not b)_
print ( Does a and C not_poin tS to game
me mo locationSZ" ais not C
Output
Do eg a and b pointS to Same memOry

locations 2 True
Does a andC points to Same memOTy
ocations ? fodse
Does a and b not pointS to Same memoi
locations ? Pcd s e
Does a and C notpointS to Same memany
locaticnS 2 True

Python Operator Precedence:


The Table showsthe oper otor precedence from
to lowQSL.
highest
Operatcor Descriptian
Expanentiation (rse to the puer)
n,t Complementunaru plus and munuS
1 , %, 1 Multiply divide madulo g bar Divisioa
Addition anc Subtr.ction
Right shift and Left shift
& Bitwise AND Operator
A, Bitwise exclusive OR and Reqular OR
4,k,,>= Relation.al OperotonS
Equality operaborS
t ,*=E,1I= Assignment operat or
i S i s not Identity operators
i n not in Membershup ope1atorS
and, or , not Logi ca operoto1S
T
Yanqe Function
1t is veny nec
essar to
diScuS 3 On ianqe
function, befors discussian on
con trol
flow StatementS and loops.
Every fxample an for Loop that we Seein
Some prOgomS, 01e using 1ange () functian.
IE makesan impact that the rangec) fundion
is a mandat ory pat of lo op But it is not
ike that
The range O function by defalt, 1etuIOS
a listbased on provi ded paiameterS.
This fun ction has falloing sianatuie.
Tange Stat-val ue, end-vodue 9tep)
Because at asSiqned default - arqument
to each three paiameterS e can uSe

this function with th ree cdi ffexenta


possi bilities.
-when used with one parameter it will

ConSider thispa1ame.ter as end-value


and 1eturns a 1anqe fiom to end-value--1
for eam ple :

a J i s t (1anqe Cio)
print a )
will ies ult a9

I o,L2,3, 4, 5,6,7, 8,9]


-In Tuple
a tuple (Tange c10)
print(a)
w eSult ag:
Co 1,2,3, 4,5, 6,7, 8,9)
T
when u s e d w i t h t u u o Porarn eterS,
it will cansider these 9a1ameterS aS
Statvalue and end-N alue
It Yeturnsa Yange Containinq volue

fiom Start-index to end-ind e - 1


for example: the statement
a ist (an qe C 15,0)
pint (a)
will 1eswt$S as
C 15 16, 7 18 19]
I n Tuple
a- tuple (van9e (5 20)
print la)
wi yeSuftS as
C15, 16 17, 18,19.)
when uSed with thee paiametersit
wil conSider the se parameters a s
StactNolue,end-value and Step.
It re.sults as a ranqe containinq val ue

fiom start- index to end-index - / with

specifiedStep(inciement_/decement)
having
having two paiamete1S, the Stepis by-
dlefalt t l
for e1ample-
alist( Tanqe C,20,+2))
priOtCa)
wi_1esult_ aS_
[ , 3 ,5, 7,9, 13, , 15,17, 19
yoA Can even try following 9tCte PmeTIt
a- list yanqe (205 2
print a)
will eSult a s
[20, 18, 16, 14,12, 108, 6]

Conto Flou 9t cukement.gs


-In qeneroal, Statements ane exeuted
Sequen tially 1e. the first Statement i n
a function i s ezecuted tirstfollawecd by
the Secand, and So on.
-Like other proq1amminq languaqeS Puthon
al3o p1gviodesyariouS Cantrol flou StatementS
that allow for more complicate d_ ezecutian
situations.
These Contral flow StatementS include
. Conditional gtatements CDeision makinq Statemens
. Loap contiol Statements (Ite ratiye Statements)
These cantiol flou Statements aie ezplai ned
asfollowSi
Conditiond stotementS OR
Decision Making 3tatementS '-
The condition Statement exccut es the
the
block ot Stotements based on correctnesg
of Candition ie. DeciSton tMaking 9tatementS
ae used when we wanta 9et at ingtructi ong
shold be czecuted in ona gituation, and
different instructions Should be executeq
in another situoti on.
Decision makinq can be implemented in
Python uSing follo winq Statement
J
i f Statement
it e lse Stotement
t - elif - else Statement
4 nested if Statement
These conditionad 9tatements are
4eplaned aS follow9:
The If Statementi
The it- Statement is aid standard
Stulewhere blocK of Statememt gets
ezecuted tprovided condition is Tue
Sunta
if Cond1tion
gtatements 1
StatementS- 2

Statemnent-- n
The mos t impo1tant thing 1s
Python's
Ony
Ony contral flow 9tatement Containsg a colon
and then inden tation to
Specitythe bods.
Here, if the speci Pie d condition is rue
then anly block of statement ezet utes
a»ly
atherwise gets Skipped.
The Pollo winq python prOqTam illustiates
the only ane if condition
print Before if Statement")
if a> 10
print ("a is greater than 10 )
print( After if Statement)

O/P
Befo re it statement
a is gieater than 10
After f Statem ent

Also in mogt of the logica1e qwrement 9


we use multiple-if statement.s; where all

if-StatemmentSare independent
following pOq1am ContainS One prom ptolso
W e can
me.9saqe in inpuut ) Stotement
use logical operators to chec multiple condiio
ng.
The fallowinq Pythonprogram 1Sezample
-it Ctatements to find targest
of
of multiple
thiee valueS
Py thon Proqram:
print ("Enter three numberS
n=intCinput O)
haint(input )
n3int(inputO)
if n n 2 and n n3
print( n1, "is larqes t ")
if ngn and ng Da
print (n2, "is larqeSt "
itn3 n and ngn2:
pxint Cngis lasqest")
O/p
Enter thiee numberS

20
30
30 is larqest

.if elsa Stotement


-The if- statement onls evaluoates to True
esult, but w e coan also eval uate false
esaltby usin9 if-else Statement,
Suntaz
i f condition:
Statement- 1
Statement-2

S t a t em e n t - n
ese
Statement - 1

Statement - 2

Statement-n

The if-block will execute if provided


condition is r u e other wISe else-bloc
will be executed.
The following progiam that checkS whether
entered number is even or odd, by usinq
if. else Statement

Python Proqram
print ( Enter a number: ")
num int(input )
f num %2:<o:
print Cnum, " is even")

else
print (num TS Odd
/p
Enter a numbder

20 is odd

We can also check canditions by uSing


by
membershup opeiatoi
list i : [ lo,40,20,555,"Ravi",100J
if 1o in list 1
print ("list 1 ontainS 10")
else

pint (List i does not con tainS 1o ")


if 20 in list 1
print("List 1 Contoin9 20"")_
else
print("List 1 does not Conbains 20")

0/p
List 1 contouns 10
List1does not contoin 2a

3 i f - elif -else Statement:


Tn multiple- if StatementS, all if-
Statements aie independent.
It means it will test all condition s
even ifone if- condition is satisfied
- Testinq all if-conditions will waste
executLoD tim .
The solution to this situation i s elit

Statement:
Guntaz:
if condition-1
Statement-1
Statement-2

Statement-n_
elif condition-2:
Statement-1
Statement -2

Statement -n
elif con dition-n:
Stctem ent- 1
Stoutement-2

SEatement-n
else
Stotement-1

9tatement-2

Statem ent -n

will 9kip testing Other


In elif-Statementit
Condi Hong if ans_one conodibion 1esult g T7ue,
then
And if all conditions 1eSwtS Palse
last default else block executes
The wheie we check
followinq example
whether entered character 1S upper CaSe
letter o lower case etteer of digitof

Specia sumbol.

-Python Proqram
va input("Enter any character")
ch ord (val)
if ch2 65 and ch<-9o:
print"It is an upper case Jetter")
elif ch2= 97 and ch<= 122

print (IE JS a lowercase letter")


elif c h : 4 8 ch<:
and 57:

print "It is a digit )


else
print "It is a special SymbolT)

C/p
Enter a n eharacter

N
etter
Tt is an uppercase
4 nested-if Statement :
The nested-if Statements are algo test
nested Conditiong.
Suntax :

if condition-1:
if condition -2:
if condition-n:
Statene nt - 1
Stctement -2

Statem ent - n

The erecwtion of StatementS depend9 on


of allL if conditiong,
correctness
ezecute if all aonditions
The Statem entS uwi
are True.
followinq pro9 ram that find9 larqest
The
nested-if
of th ree
of
numberS by uSing
State ment s.

You might also like