Professional Documents
Culture Documents
Handout #2
IF and IF-ELSE
CONDITIONALSTATEMENTS
Alsoknownascontrolstatements,conditionalstatementsareusedtocontrolthesequenceof
executionofthestatementsinyourprogram.
IFSTATEMENT
Ifstatementsareusedtoexecuteastatementunderacertaincondition.
ThegeneralPythonsyntaxforasimpleifstatementis
ifcondition:
indentedStatementBlock
whereifisareservedword,
conditionisalogicalexpression(returnsbool,i.e.,TrueorFalse),and
indentedStatementBlockcontainsthestatementsthattheprogramwilldoifthe
conditionissatisfied.
Forexample,intheairport,yourbaggageallowanceisonly5kgs.Ifyouexceed5kgs,youwill
needtopayanPhp50foreachadditionalkilo.Forthisproblem,wecancreateaprogramthat
determinesifapassengerneedstopayadditionalchargesdependingontheweightofhis/her
luggage.
weight=float(input("Whatistheweightofyourluggage?"))
if(weight>5):
print("Youneedtopayadditional",(weight5)*50,"foryourluggage.\n")
printf("Haveasafeflight!")
Theprogramfirstaskedfortheweightoftheluggage.Thenafterthat,anifstatementisused.If
theweightenteredisgreaterthanfive,thentheprogramwilldotheindentedstatementafterthe
ifstatementwhichistoprinthowmuchadditionalchargethepassengershouldpay.Iftheweight
isnotgreaterthanfive,thenitwilljustprintagreetingtothepassenger.
IFELSESTATEMENTS
Ifelsestatementsarejustamodifiedversionoftheifstatement.Ifelsestatementsallowsyouto
dosomethingiftheconditiongivenisnotsatisfied.
ThegeneralPythonsyntaxforasimpleifelsestatementis
ifcondition:
indentedStatementBlockForIf
else:
indentedStatementBlockForElse
1of3
Handout #2
IF and IF-ELSE
Agoodexampleofusingifelsestatementsiswhencreatingaprogramthetellsifastudent
passedorfailedasubject.
grade=int(input(WhatisyourgradeinCS11?))
if(grade<55):
print(Sorrybutyoufailedthecourse.)
else:
print(Congratulations!Youpassedthecourse!)
print(ThankyoufortakingCS11!)
Thistime,theprogramaskedforthegradeofthestudentinCS11.Ifthegradeinputtedisless
than55,whichisthepassinggrade,thenitwilltellthestudentthats/hefailed.Else,itwilltellthe
studentthats/hepassed.
Youneedtorememberthatonceaconditionissatisfied,itwillonlydotheindentedstatements
afterit.Therefore,indentionmustalwaysbechecked.
NESTEDIFELSESTATEMENTS
Youcanalsoputanif/ifelsestatementinthecodeblockofanifstatement.
Oneexamplewhereyoucanusenestedifelsestatementsiswhenyouclassifyclothsizes.
waistCM=int(input(Waistcircumferenceincm:))
ifwaistCM<64:
#iflessthan64,sizeisXS
print(XS)
else:
#elsesizeiseitherS,M,L,orXL
ifwaistCM<69:
#ifwaistCM<69andwaistCM>63,S
print(S)
else:
#elsesizeiseitherM,L,orXL
ifwaistCM<74:
#ifwaistCM<74andwaistCM>68,M
print(M)
else:
#elsesizeiseitherLorXL
ifwaistCM<79:
#ifwaistCM<78andwaistCM>73,L
print(L)
else:
#else,sizeisXL
print(XL)
Inthecodeabove,theprogramfirstchecksifthevariablewaistCMislessthan64.Iftrue,the
programwillprintXS.Else,ifwillcheckfortheothersizes(S,M,L,XL).
Itwillthencheckforthenextsize,S,whichislessthan69.Sincewealreadycheckedif
waistCMislessthan64,thenwealreadyknowthatitisgreaterthan63.Thatmeans,onthe
secondifstatement,wearecheckingifwaistCMisintherange[64,68].Ifitisintherange,the
programwillprintS.Else,itwillcheckforthenextsize,M,whichisintherange[69,73],andso
onuntilitfindstherangeitbelongstoandprintitscorrespondingsize.
2of3
Handout #2
IF and IF-ELSE
IFELIFELSESTATEMENTS
Noticethatthecodeabovehasalotofindentationsandnewlines.Thisrepeatedlyincreasing
indentationcanbeannoyinganddistracting.Apreferredalternativethatavoidsallthese
indentations,istocombineeachelseandifblockintoanelifblock:
waistCM=int(input(Waistcircumferenceincm:))
ifwaistCM<64:
#iflessthan64,sizeisXS
print(XS)
elifwaistCM<69:
#ifwaistCM<69andwaistCM>63,S
print(S)
elifwaistCM<74:
#ifwaistCM<74andwaistCM>68,M
print(M)
elifwaistCM<79:
#ifwaistCM<78andwaistCM>73,L
print(L)
else:
#else,sizeisXL
print(XL)
Theabovecodedoesthesamethingthecodethatusesnestedifelsedoes,thedifferenceis
thatitlooksneaterthanthepreviousone.
3of3