Upload
others
View
7
Download
0
Embed Size (px)
Citation preview
PrefaceWhen I started teaching Python 2 years ago, I was amazed to find a variety of
learningresourcesonline.Ilearntthelanguageandstartedteachingittomystudents.Butitbecameincreasinglydifficulttoputtogethersomeconceptsandcreateapplications.Thefreetutorialsdidnotexplain,forexample,howtopopulateadictionarywithvaluesfromtheuser.It tookalotoftimetorefergoodbooksandcreateteachingnotes.Thesenoteshavetakentheshapeofthisbook.Pythonisasimpleyetpowerfulprogramminglanguage.Theentire focusof thisbook is tosimplify thebasicconceptsofPython. It isbasedonsyllabusofschoolsandengineeringcollegesandshouldcatertoanybeginnerwishingtolearnPython.
Thebookisorganizedinto13chaptersasfollows
Chapter 1 deals with installation and running the first Python program. ThischapterneedstobetaughtinthelabandifPythonisalreadyinstalled,itshouldtake10-20 minutes to understand interactive and script modes. Chapter 2 explains variables,datatypesandoperators.ThereareafewspecialoperatorsinPython.Chapter3explainsthefunctionsinPython.Italsoexplainsthevarioustypesofarguments.Chapter4dealswith the control structures. It contains a lot of simple programs using if, for andwhilestructures. Chapter 5 explains the string module functions. Simple programs using thebuilt in functions are explained. Chapter 6 explains the handling of lists. Various listfunctions are also explained. Chapter 7 explains the Python dictionaries and theirapplication.Chapter8explainstuplefunctions.
Chapter9 introduces theconceptsofclasses,objectsandinheritance.Chapter10explains data structures. Searching and sorting algorithms are explained. Stacks andQueuesareexplainedwithPython implementation.Chapter11explains thedata files inPython.FilesareabeautyofthislanguagecomparedtoC++.Theeasewithwhichwecantalk to files from Python is amazing. Chapter 12 explains exception handling andgenerator functions. Chapter 13 has 4 interesting projects. These were done by mystudents aspart of their projectwork.Similar to files, database access is also relativelysimpleinPython.ThecodegiveniswithSQLServer.
Thisbook is intended tobesimpleyeteffectiveforstudentswhowoulduse thisready reference for better preparation. All programs have been thoroughly tested and
screenshotsareprovidedaftereveryprogramforbetterunderstanding.
Author
Acknowledgement
Bookwritinghasbeenmyhobbyforthepast3yearsanditrequiresalotoftimeandhardwork.MyentirefamilyhasstoodbymethroughoutmybookwritingjourneyandIthankthemallfromthebottomofmyheart.
Iwouldliketothankmyhusband,Mr.Karthik,forthetechnicalreviewofthebook.Hehasbeenaconstantsourceofmotivation.Mykids,NiranjanandNivedha,gavemethetimeandspaceforbookwriting.
Myfriendsandcollegueswerealwayssupportiveingivingmeconstructivefeedbacktoimprovemybooks.
Lastbutnottheleast,Iwouldliketothankeachoneofmystudents.Istatedwritingbooksforthemandeachsessionwiththemhaskindlednewideas.
Ithankthereadersforyourcontinuedsupport.Yourfeedbackisveryvaluableforimprovingthisbook.
Pavithra
Email:[email protected]
Contents
Chapter1:IntroductiontoPython
InstallingPython2.7&Executingthefirstprogram
Chapter2:Variables,datatypesandoperators
Keywords
Datatypes
Datatypeconversions
Operators
Inputandoutput
SolvedQuestions
PracticeProblems
Chapter3:FUNCTIONS
Built-infunctions
Modules
User–definedfunctions
ParametersandArguments
Anonymousfunctions
Scopeofvariables
SolvedQuestions
Practiceproblems
Chapter4:Conditionalconstructsandlooping
Conditionalconstructs
Iterationstructures
SolvedPrograms
PracticeProblems
Chapter5:Strings
AccessingValuesinStrings
UpdatingStrings
EscapeCharacters
StringSpecialOperators
StringFormattingOperator
Built-instringfunctions
Stringconstants
RegularexpressionsandPatternmatching
Functionsfromremodule
SolvedPrograms
PracticeProblems
Chapter6:Lists
Listoperations
Slicing
Negativeindexing
Listfunctions
Matrices
Matriximplementationusinglist
SolvedQuestions
Practiceproblems
Chapter7:DICTIONARIES
Creatingadictionary
CharacteristicsofPythonDictionaries
AccessingValuesinDictionary
UpdatingDictionary
DeleteDictionaryElements
Built-inDictionaryFunctions&Methods
SolvedPrograms
PracticeProblems
Chapter8:Tuples
TupleCreation
Tupleinsertion
Tupleinitialization
TupleAssignment
TupleSlices
UpdatingTuples
DeleteTupleElements
BasicTuplesOperations
Built-inTupleFunctions
SolvedPrograms
PracticeProblems
Chapter9:Classes,ObjectsandInheritance
Namespaces
Definingclasses
Objects
Self
ACCESSINGATTRIBUTES
BUILT-INCLASSATTRIBUTES
__del()__ordestructor
__str()__
Privatevariables
DYMANICALLYADDINGMETHODS
DynamicClassMethodAddition
DynamicInstanceMethodAddition
StaticMethods
DestroyingObjects(GarbageCollection)
Inheritance
Formsofinheritance
BaseOverloadingMethods
SingleInheritance
MULTILEVELINHERITANCE
MultipleInheritance
MethodOverriding
Abstractmethods
SolvedQuestions
PracticeQuestions
Chapter10:Datastructures
Lineardatastructure
Non-Lineardatastructure
AlgorithmsonListOperations
Traversal
Insertion
Deletion
ArraySearching
ArraySorting
Stacks
Applicationofstacks
Queue
Deque(Double-endedqueues)
CircularQueues
SolvedExamples
PracticeQuestions
Chapter11:DATAFILEHANDLING
OpenFunction
FileopeningModes
Thefileobjectatrributes
Openingafile
FileMethods
osmodulefunctions
Operationsontextfiles
Writing/Creatingatextfile
Readingfromatextfile
Traversal/Display
Deletion
Updation
RandomAccess
Binaryfiles
Writinginabinaryfile
Readingfromabinaryfile
BinaryfileManipulation
SolvedQuestions
PracticeQuestions
Chapter12:ExceptionHandling&Generators
Exceptionhandling
Raise
User-DefinedExceptions
Generatorfunctions
SolvedExamples
PracticeQuestions
Chapter13:SampleApplications
Project1:Inventorymanagement
Project2:Quiz
Project3:Databasesoperationsusingpython
Project4:CALCULATOR
Solutionstopracticequestions(selected)
Referencebooks
Weblinks
Otherbooksbythesameauthor
Chapter1:IntroductiontoPython
Pythonwas createdbyGuidoVanRossum in1991.Pythongot its name fromaBBCcomedyseries–“MontyPython’sFlyingcircus”.
Pythonisaninterpretedhigh-levellanguage,whichmakesitfasterthanothercompiledlanguages.Thehigh-leveldatatypesallowustoexpresscomplexoperationsinasinglestatement.Statementgroupingisdonebyindentationinsteadofbeginningandendingbrackets. No variable or argument declarations are necessary. It is suitable as anextension language for customizable applications. It has a wide library of add-onmodules.Itisaplatformindependentprogramminglanguage
InstallingPython2.7&ExecutingthefirstprogramPythonisafreeware.AllexamplesinthisbookareofPython2.7.
ToinstallPython,gotohttp://www.python.org/download/releases/2.7/
IDLEisthestandardmostpopularPythondevelopmentenvironment.IDLEisanacronymofIntegratedDevelopmentEnvironment.
1.WeneedtogotoStart � IDLE
Fig1.1:IDLEIcon
WhenwestartuptheIDLEfollowingwindowwillappear.
Fig1.2:IDLEwindow
>>>promptmeansthattheinterpreterisexpectingapythoncommand
…indicatesthattheinterpreteriswaitingforadditionalinputtocompletethecurrentstatement.
WetypePythonexpression/statement/commandafterthepromptandPythonimmediatelyrespondswiththeoutputofit.
Fig1.3:Firstprogram
Aftertypingapythoncommand,pressEnter
Fig1.4:Outputscreenshot
Pythonininteractivemodehelpsustolearnbetterbutwecannotsavethestatementsforfurtheruse.Interactivemodeissuitedonlyforbeginnersorfortestingsmallpiecesofcode.
Inscriptmode,wetypePythonprograminafileandthenusetheinterpretertoexecutethecontentfromthefile.Workingininteractivemodeisconvenientforbeginnersandfortestingsmallpiecesofcode,aswecantestthemimmediately.Butforcodingmorethanfewlines,weshouldalwayssaveourcodesothatwemaymodifyandreusethecode.
Steps:
1. FirstgotoFile � NewWindow
Fig1.5:Scriptmode1
2. Wecanseeablankwindowpoppingup
Fig1.6:Scriptmode2
3. WritethePythoncode
Fig1.7:Scriptmode3
4. Saveitwith“.py”extension
Fig1.8:ScriptMode4
5. ExecutebypressingShift+F5keyorrunoption
Fig1.9:ScriptMode5
6. Verifytheoutput
Fig1.10:ScriptMode6
Chapter2:Variables,datatypesandoperators
Variablesarereservedmemorylocationstostorevalues.Avariablehasaname,atypeandavalue.
InlanguageslikeC,C++orJavaweneedtoexplicitlydeclarevariablesPythonvariablesneednotbeexplicitlydeclared.Thedeclarationhappensautomaticallywhenweassignavaluetoavariable.
Ex:
Name=“India”#Astring
(NamevalueType)
Wecanassignmultiplevaluestomultiplevariablesinasinglestatement.
a,b,c=1,2.0,“Hello”
Example2.1:Whatarethevaluesofxandyafterthecodeisexecuted.
x=3
y=4
z=x+y
z=z+1
x=y
y=5
printx,y,z
Afterthesefourlinesofcodeareexecuted,xis4,yis5andzis8.
1.xstartswiththevalue3andystartswiththevalue4.2.Inline3,avariableziscreatedtoequalx+y,whichis7.3.Thenthevalueofzischangedtoequalonemorethanitcurrentlyequals,changingitfrom7to8.
4.Next,xischangedtothecurrentvalueofy,whichis4.
5.Finally,yischangedto5.Notethatthisdoesnotaffectx.6.Soattheend,xis4,yis5,andzis8.Rulesfornamingvariables
1.Variablenamescancontaina-z,A-Z,0-9and‘_’(underscore)2.Variablenameshouldnotbeginwithadigit3.Itshouldnotbeakeyword4.Itcanbeofanylength
5. Variablenamescannotcontainspaces.6. Casematters—forinstance,tempandTemparedifferent.
Example2.2:Whichofthefollowingvariablenamesareinvalid?Justify.
a)tryb)123Helloc)abc@dd)sum
Ans:
a)try–It’sakeywordandcan’tbeusedasavariablename
b)123Hello–Variablenamescan’tstartwithadigit
c)abc@d–Specialcharactersaren’tallowedinvariablenames.
Amutableobjectexhibitstime-varyingbehavior.Changestoamutableobjectarevisiblethroughallnamesboundtoit.Ex:lists
Animmutableobjectdoesnotexhibittime-varyingbehavior.Thevalueofimmutableobjectscannotbemodifiedaftertheyarecreated.Theycanbeusedtocomputethevaluesofnewobjects.Ex:strings,tuples
Keywords
Fig2.1:Pythonkeywordlist
DatatypesDatatypeisasetofvaluesandtheallowableoperationsonthosevalues.Python
hasagreatsetofusefuldatatypes.Python’sdatatypesarebuiltinthecoreofthelanguage.Theyareeasytouseandstraightforward.
Fig2.2:PythonDatatypes
Numberscanbeeitherintegersorfloatingpointnumbers.
Asequenceisanorderedcollectionofitems,indexedbyintegersstartingfrom0.Sequencescanbegroupedintostrings,tuplesandlists.
Stringsarelinesoftextthatcancontainanycharacters.Theycanbedeclaredwithsingleordoublequotes.
Listsareusedtogroupotherdata.Theyaresimilartoarrays.
Atupleconsistsofanumberofvaluesseparatedbycommas.
Asetisanunorderedcollectionwithnoduplicateitems.
Adictionaryisanunorderedsetofkey:valuepairswherethekeysareunique
Datatypeconversions
Thereareseveralbuilt-infunctionstoperformconversionsfromonetypetoanother.
Function Description
int(x[,base]) Convertsxtoaninteger.basespecifiesthebaseifxisastring.
long(x[,base]) Convertsxtoalonginteger.basespecifiesthebaseifxisastring.
float(x) Convertsxtoafloating-pointnumber.
complex(real[,imag])
Createsacomplexnumber.
str(x) Convertsobjectxtoastringrepresentation.
repr(x) Convertsobjectxtoanexpressionstring.
eval(str) Evaluatesastringandreturnsanobject.
tuple(s) Convertsstoatuple.
list(s) Convertsstoalist.
set(s) Convertsstoaset.
dict(d) Createsadictionary.dmustbeasequenceof(key,value)tuples.
frozenset(s) Convertsstoafrozenset.
chr(x) Convertsanintegertoacharacter.
unichr(x) ConvertsanintegertoaUnicodecharacter.
ord(x) Convertsasinglecharactertoitsintegervalue.
hex(x) Convertsanintegertoahexadecimalstring.
oct(x) Convertsanintegertoanoctalstring.
Table2.1:PythonDataconversionfunctions
Example2.3:Programthatcomputestheaverageoftwonumbersthattheuserenters.
num1=int(raw_input(‘Enterthefirstnumber:’))
num2=int(raw_input(‘Enterthesecondnumber:‘))
print(‘Theaverageofthenumbersyouenteredis‘,(num1+num2)/2)
Forthisprogramweneedtogettwonumbersfromtheuser.Wegetthenumbersoneatatimeandgiveeachnumberitsownname.Allmultiplicationsanddivisionsareperformedbeforeanyadditionsandsubtractions,sowehavetouseparenthesestogetPythontodotheadditionfirst.
OperatorsOperatorsarespecialsymbolswhichperformsomecomputation.Operatorsand
operandsformanexpression.
Pythonoperatorscanbeclassifiedasgivenbelow.
Fig2.3:Pythonoperatortypes
Let’sexploreeachoftheseoperatorsindetail
ArithmeticOperators
Arithmeticoperatorshelpustoperformvariousarithmeticcalculations.Thearithmeticoperatorsareexplainedinthetablebelow.Let’sassumevalueofa=2andb=3
Operator Description Example
+ Addition-Addsvaluesoneithersideoftheoperator
a+bresultsin5
- Subtraction-Subtractsrighthandoperandfromlefthandoperand
a–bresultsin-1
* Multiplication-Multipliesvaluesoneithersideoftheoperator
a*bresultsin6
/ Division-Divideslefthandoperandbyrighthandoperand
a/bresultsin0
% Modulus-Divideslefthandoperandbyrighthandoperandandreturnsremainder
a%bresultsin2
** Exponent-Performsexponential(power)calculationonoperators
a**bresultsin8
// FloorDivision-Thedivisionofoperandswheretheresultisthequotientinwhichthedigitsafterthedecimalpointareremoved.
11//2resultsin5
11.0//2.0resultsin5.0
Table2.2:Pythonarithmeticoperators
Relational/ComparisonOperators
Theseoperatorshelpustomakedecisionsbasedoncertainconditions.
Operator Description Example
== Checksifthevalueoftwooperandsareequalornot,ifyesthenconditionbecomestrue.
(a==b)isnottrue.
!= Checksifthevaluesoftwooperandsareequalornot,ifvaluesarenotequalthenconditionbecomestrue.
(a!=b)istrue.
<> Checksifthevalueoftwooperandsareequalornot,ifvaluesarenotequalthenconditionbecomestrue.
(a<>b)istrue.Thisissimilarto!=operator.
> Checksifthevalueofleftoperandisgreaterthanthevalueofrightoperand,ifyesthencondition
(a>b)isnottrue.
becomestrue.
< Checksifthevalueofleftoperandislessthanthevalueofrightoperand,ifyesthenconditionbecomestrue.
(a<b)istrue.
>= Checksifthevalueofleftoperandisgreaterthanorequaltothevalueofrightoperand,ifyesthenconditionbecomestrue.
(a>=b)isnottrue.
<= Checksifthevalueofleftoperandislessthanorequaltothevalueofrightoperand,ifyesthenconditionbecomestrue.
(a<=b)istrue.
Table2.3:Pythonrelationaloperators
AssignmentOperators
Theseoperatorsassigntherightsidevaluetotheleftsidevariable.
Operator Description Example
= Simpleassignmentoperator,Assignsvaluesfromrightsideoperandstoleftsideoperand
c=a+bwillassignthevalueofa+bintoc
+= AddANDassignmentoperator,Itaddsrightoperandtotheleftoperandandassigntheresulttoleftoperand
c+=aisequivalenttoc=c+a
-= SubtractANDassignmentoperator,Itsubtractsrightoperandfromtheleftoperandandassigntheresulttoleft
c-=aisequivalentto
c=c–a
operand
*= MultiplyANDassignmentoperator,Itmultipliesrightoperandwiththeleftoperandandassigntheresulttoleftoperand
c*=aisequivalenttoc=c*a
/= DivideANDassignmentoperator,Itdividesleftoperandwiththerightoperandandassigntheresulttoleftoperand
c/=aisequivalenttoc=c/a
%= ModulusANDassignmentoperator,Ittakesmodulususingtwooperandsandassigntheresulttoleftoperand
c%=aisequivalenttoc=c%a
**= ExponentANDassignmentoperator,Performsexponential(power)calculationonoperatorsandassignvaluetotheleftoperand
c**=aisequivalenttoc=c**a
//= FloorDivisionANDassignsavalue,Performsfloordivisiononoperatorsandassignvaluetotheleftoperand
c//=aisequivalenttoc=c//a
Table2.4:Pythonassignmentoperators
Bitwiseoperators
Bitwiseoperatorworksonbitsandperformbitbybitoperation.Assumeifa=65;andb=12;Nowinbinaryformattheywillbeasfollows:
a=01000001
b=00001100
a&b=00000000
a|b=01001101
a^b=01001101
~a=10111110
Table2.5:Bitwiseoperations
ThetablebelowliststhebitwiseoperatorsinPython.Let’sassumea=65andb=12forthisexample.
Operator Description Example
& BinaryANDOperatorcopiesabittotheresultifitexistsinbothoperands.
(a&b)resultsin0(00000000)
| BinaryOROperatorcopiesabitifitexistsineitheroperand.
(a|b)resultsin77whichis1001101
^ BinaryXOROperatorcopiesthebitifitissetinoneoperandbutnotboth.
(a^b)resultsin77whichis1001101
~ BinaryOnesComplementOperatorisunaryandhastheeffectof‘flipping’bits.
(~a)resultsin-66whichis10111110.
<< BinaryLeftShiftOperator.Theleftoperandsvalueismovedleftbythenumberofbitsspecifiedbytheright
a<<2resultsin260whichis100000100
operand.
>> BinaryRightShiftOperator.Theleftoperandsvalueismovedrightbythenumberofbitsspecifiedbytherightoperand.
a>>2resultsin16whichis10000
Table2.6:Pythonbitwiseoperators
LogicalOperators
TherearefollowinglogicaloperatorssupportedbyPythonlanguage.
Operator Description Example
and LogicalANDoperator.Ifboththeoperandsaretruethenthenconditionbecomestrue.
a=5b=10
(aandb)istrue.
or LogicalOROperator.Ifanyofthetwooperandsarenonzerothenthenconditionbecomestrue.
(aorb)istrue.
not LogicalNOTOperator.Usetoreversesthelogicalstateofitsoperand.IfaconditionistruethenLogicalNOToperatorwillmakefalse.
not(a)isfalse.
Table2.7:Pythonlogicaloperators
MembershipOperators
Pythonhasmembershipoperators,whichtestformembershipinasequence,suchasstrings,lists,ortuples.Therearetwomembershipoperatorsexplainedbelow:
Operator Description Example
In Evaluatestotrueifitfindsavariable Y=[]
inthespecifiedsequenceandfalseotherwise.
Ifxiny:
return1ifxisamemberofsequencey.
notin Evaluatestotrueifitdoesnotfindsavariableinthespecifiedsequenceandfalseotherwise.
Y=[]
Ifxnotiny:
herenotinresultsina1ifxisnotamemberofsequencey.
Table2.8:Pythonmembershipoperators
IdentityOperators
Identityoperatorscomparethememorylocationsoftwoobjects.TherearetwoIdentityoperatorsexplainedbelow:
Operator Description Example
Is Evaluatestotrueifthevariablesoneithersideoftheoperatorpointtothesameobjectandfalseotherwise.
xisy,hereisresultsin1ifid(x)equalsid(y).
isnot Evaluatestofalseifthevariablesoneithersideoftheoperatorpointtothesameobjectandtrueotherwise.
xisnoty,hereisnotresultsin1ifid(x)isnotequaltoid(y).
Table2.9:Pythonidentityoperators
Operatorprecedence
Thefollowingtablelistsalloperatorsfromhighestprecedencetolowest.
Operator Description
** Exponentiation(raisetothepower)
~+- Complement,unaryplusandminus(methodnamesforthelasttwoare+@and-@)
*/%// Multiply,divide,moduloandfloordivision
+- Additionandsubtraction
>><< Rightandleftbitwiseshift
& Bitwise‘AND’
^| Bitwiseexclusive`OR’andregular`OR’
<=<>>= Comparisonoperators
<>==!= Equalityoperators
=%=/=//=-=+=*=**=
Assignmentoperators
is,isnot Identityoperators
innotin Membershipoperators
notorand Logicaloperators
Table2.10:Operatorprecedence
Example2.4:ThefollowingexampleillustratesoperatorprecedenceinPython.
a=1
b=2
c=3
d=4
e=0
e=(a+b)*c/d#(3*3/4)=9/4
print“Valueof(a+b)*c/dis“,e
f=((a+b)*c)/d#(3*3)/4=9/4
print“Valueof((a+b)*c)/dis“,f
g=(a+b)*(c/d);#(3)*(3/4)=0
print“Valueof(a+b)*(c/d)is“,g
h=a+(b*c)/d;#1+(2*3)/4=1+6/4=10/4
print“Valueofa+(b*c)/dis“,h
Inputandoutput
Pythontakesthedataenteredbytheuserusing2functions
raw_input():raw_input([prompt])
input():input([prompt])
raw_input()
Thefunctiontakesexactlywhatistypedfromkeyboard,convertsittostringandstoresitinthevariable.
>>>x=raw_input(“Enteryourname”)
Enteryourname
Ifweneedtogetnumericvaluesfromtheuser,weneedtouseint().
>>>y=int(raw_input(“Entertherollno.”))
Entertherollno
Thefunctionint()convertsthestringtointeger.
input()
input()evaluatestheinputtypedatthepromptanditexpectsavalidpythonexpression.Iftheinputprovidedisn’tcorrecttheneitherasyntaxerrororexceptionisraisedbyPython.
print()
print()communicatestheprogram’sresulttotheenduser.Itevaluatestheexpressionbeforeprintingitonthemonitor.
print()movestothenextlineafterprintingonestatement.
>>>print4+6
10
Toprintinthesamelinewecanusecomma’s
print“I”,
print“Love”,
print“Python”
Fig2.4:print()
Comments
Programnoteswhichexplainthepurposeofaprogramareknownascomments.InPython,commentscanbe
singleline:startswith“#”
#calculatesimpleinterest
multiline:startswith‘’’’’’
“””calculatesimpleinterest
Usingformula(pnr)/100“””
SolvedQuestions1. Writeaprogramtogetthesideofasquarefromtheuserandprintitsarea.
Ans:
side=int(raw_input(“Enterthesideofasquare”))
area=side*side
print“Areaofsquare=”,area
2. Writeaprogramtocalculatesimpleinterest.
Ans:
principal=float(raw_input(“Entertheprincipalamount”))
years=float(raw_input(“Entertheno.ofyears”))
rate=float(raw_input(“Enterrateofinterest”))
si=(principal*years*rate)/100
print“SimpleInterest=”,si
3. Thefollowingprogramisnotgivingtheintendedoutput.Inputgivenis4andtheexpectedoutputis16.Findtheerror.
N=raw_input(“Enternumber”)
S=N*N
printS
Ans:
Thenumberistreatedasastring.So,ifweconvertittointegerwewillgetthedesiredoutput.
N=int(raw_input(“Enternumber”))
PracticeProblems1. Writeacodethataskstwopeoplefortheirnames;storesthenamesinvariables
calledname1andname2;sayshellotobothofthem.2. WriteaprogramtogetatemperatureinCelciusandconvertitintoFarenheitusing
theformulaF=C*9/5+32.3. Predicttheoutput
a)print4*5+9*2–8%3+9
b)print8.7//2–1+4ornot2==4andnot2**4>6*3
Chapter3:FUNCTIONS
Functionsarethemostimportantbuildingblocksinanyprogramminglanguage,especiallyPython.Afunctionisablockofstatementsthatperformacomputation.Thelinesofcodeinsideafunctionareexecutedsequentially.
Fig3.1:Functions
Built-infunctions
Built-infunctionsarethefunctionsthatarebuiltintoPythonandcanbeaccessedbyaprogrammer.
Table3.1:Pythonbuilt-infunctions
Someimportantfunctionsareexplainedbelow
S.No Function Description Example
1 abs(x) Returntheabsolutevalueofanumber.Theargumentmaybe
abs(-4.0)
aplainorlongintegerorafloatingpointnumber.Iftheargumentisacomplexnumber,itsmagnitudeisreturned.
4.0
2 cmp(x,y) Comparethetwoobjectsxandyandreturnanintegeraccordingtotheoutcome.Thereturnvalueisnegativeifx<y,zeroifx==yandstrictlypositiveifx>y.
cmp(6,7)
-1
3 divmod(a,b) Taketwo(noncomplex)numbersasargumentsandreturnapairofnumbersconsistingoftheirquotientandremainderwhenusinglongdivision.
divmod(8,8)
(2,2)
4 len(s) Returnthelength(thenumberofitems)ofanobject.Theargumentmaybeasequence(string,tupleorlist)oramapping(dictionary).
len(“Python”)
6
5 max(arg1,arg2,*args[,key])
Returnthelargestiteminaniterableorthelargestoftwoormorearguments.
Theoptionalkeyargumentspecifiesaone-argumentorderingfunctionlikethatusedforlist.sort().Thekeyargument,ifsupplied,mustbeinkeywordform(forexample,max(a,b,c,key=func)).
max(8,56,34)
56
max(“India”,“China”,“Japan”)
‘Japan’
6 min(arg1,arg2,*args[,key]) Returnthesmallestiteminaniterableorthesmallestoftwoormorearguments.
Theoptionalkeyargumentspecifiesaone-argumentorderingfunctionlikethatusedforlist.sort().Thekeyargument,ifsupplied,mustbeinkeywordform(forexample,min(a,b,c,key=func)).
min(8,56,34)
8
min(‘India’,‘China’,‘Japan’)
‘China’
7 range(stop)
range(start,stop[,step])
Thisisaversatilefunctiontocreatelistscontainingarithmeticprogressions.Itismostoftenusedinforloops.Theargumentsmustbeplainintegers.
Ifthestepargumentisomitted,itdefaultsto1.
Ifthestartargumentisomitted,itdefaultsto0.stepmustnotbezero(orelseValueErrorisraised).
foriinrange(0,20,2):
printi,
024681012141618
8 round(number[,ndigits]) Returnthefloatingpointvaluenumberroundedtondigitsdigitsafterthedecimalpoint.Ifndigitsisomitted,itdefaultstozero.
round(0.5)
1.0
round(-2.2)
-2.0
round(3.14127,2)
3.14
9 type(object)
type(name,bases,dict)
Withoneargument,returnthetypeofanobject.Thereturnvalueisatypeobject.Theisinstance()built-infunctionisrecommendedfortestingthetypeofanobject.
str=“Python”
type(str)
<type‘str’>
a=5
type(a)
<type‘int’>
10 tuple([iterable]) Returnatuplewhoseitemsarethesameandinthesameorderasiterable‘sitems.
tuple([1,2,3,4,5])
(1,2,3,4,5)
11 id(object) Returnthe“identity”ofanobject.Thisisaninteger(orlonginteger)whichisguaranteedtobeuniqueandconstantforthisobjectduringitslifetime.Twoobjectswithnon-overlappinglifetimesmayhavethesameid()value.
a=5
id(a)
30991416L
Table3.2:Importantbuilt-infunctions
*Datatypeconversionfunctionshavebeenalreadydiscussedinchapter2
Modules
AmoduleisafilecontainingPythondefinitionsandstatements.Weneedtoimportmodulestouseanyofitsfunctionsorvariablesinourcode.
Syntax:
importmodulename1[,modulename2,…]
Example:
importmath
value=math.sqrt(25)
Syntax:
Frommodulenameimportfunctionname[,functionname]
Example:
frommathimportsqrt
value=sqrt(25)
Note:It’sagoodprogrammingpracticetoputalltheimportstatementsatthebeginningofthePythonfile.
Someimportantmodulesaremath,random,string,time,date.
Mathmodule
Someimportantfunctionsinmathmodulearelistedinthetablebelow
Function Description Example
ceil(x) Returnthesmallestintegervaluegreaterthanorequaltox.
importmath
math.ceil(40.3)
41.0
floor(x) Returnthelargestintegervaluelessthanorequaltox.
math.floor(39.9)
39.0
exp(x) Returnsex math.exp(1)
2.718281828459045
pow(x,y) Returnsxy math.pow(8,3)
512.0
sqrt(x) Returnthesquarerootofx. math.sqrt(25)
5.0
hypot(x,y)
ReturntheEuclideannorm,sqrt(x*x+y*y).Thisisthelengthofthevectorfromtheorigintopoint(x,y).
math.hypot(6,6)
8.48528137423857
degrees(x) Convertsanglexfromradianstodegrees.
math.degrees(3.14)
179.9087476710785
radians(x) Convertsanglexfromdegreestoradians.
math.radians(180)
3.141592653589793
cos(x) Returnthecosineofx. math.cos(0)
1.0
sin(x) Returnthesineofx. math.sin(0)
0.0
tan(x) Returnthetangentofx. math.tan(0)
0.0
pi Themathematicalconstantpi.
math.pi
3.141592653589793
e Themathematicalconstante
math.e
2.718281828459045
Table3.3:Mathmodule
Randommodule
Someimportantfunctionsinrandommodulearelistedinthetablebelow
Function Description Example
random.randrange(stop)
random.randrange(start,stop[,step])
Returnarandomlyselectedelementfromrange(start,stop,andstep).
printrandom.randrange(2,10)
8
printrandom.randrange(2,10)
4
random.randint(a,b) ReturnarandomintegerNsuchthata<=N<=b.
printrandom.randint(8,20)
19
random.seed([x]) Initializethebasicrandomnumbergenerator.Optionalargumentxcanbeanyhashableobject.IfxisomittedorNone,currentsystemtimeisused;
random.seed(5)
printrandom.randint(0,10)
6
printrandom.randint(0,10)
8
random.choice(seq) Returnarandomelementfromthenon-emptysequenceseq.Ifseqisempty,raisesIndexError.
printrandom.choice(“Python”)
o
Table3.4:randommodule
StringmoduleisdiscussedinChapter5
User–definedfunctions
Pythonprovidesmanybuiltinfunctions.Butwecanalsocreateourownfunctions.Thesefunctionsarecalleduser-definedfunctions.Thereareafewrulesfordefiningourownfunctions.
1. Functionblocksbeginwiththekeyword“def”followedbythefunctionnameandparantheses.
2. Thefirststatementofafunctioncanbeanoptionalstatement–docstring.Itisthedocumentationstringofthefunctionwhichcontainsessentialinformationaboutthefunctionsuchas
purposeofafunction
typesofparameters
returnvalues
3. Anyinputparametersshouldbeplacedwithintheseparameters.4. Thestatementreturn[expression]exitsafunction,optionallypassingbackan
expressiontothecaller.AreturnstatementwithnoargumentsisthesameasreturnNone.
5. Bydefault,parametershaveapositionalbehaviour,andweneedtoinformtheminthesameorderastheyweredefined.
Example3.1:Functiontoadd2numbers
defadd(a,b):
”’Thisfunctionsadds2numbers”’
c=a+b
returnc
ParametersandArguments
Parametersarethevaluesprovidedintheparenthesisinthefunctionheaderwhenwedefinethefunction.Argumentsarethevaluesprovidedinfunctioncall/invokestatement.
Fig3.2:Functionarguments/parameters
Fig3.3:Typesofparameters
Requiredargumentsaretheargumentspassedtoafunctionincorrectpositionalorder.Somefunctionsrequiretheargumentstobeprovidedforalltheparametersandorderofargumentsshouldbethesameasinthedefinition.
Defaultargumentsassumeadefaultvalueifavalueisnotprovidedinthefunctioncallforthatargument.Aparameterhavingadefaultvalueinfunctionheaderbecomesoptionalinfunctioncall.Functioncallmayormaynothavevalueforit.Theyareused
Toaddnewparameterstotheexistingfunction
Tocombinesimilarfunctions
Toprovidegreaterflexibilitytoprogrammers
Keywordargumentsallowsustoskipargumentsorplacethemoutoforderbecausetheinterpreterisabletousethekeywordsprovidedtomatchthevalueswithparameters.Thecallingfunctionidentifiestheargumentsbytheparametername.ThisisauniquefeatureofPythonwherewecanwriteanyargumentinanyorderprovidedwenamethearguments.Wecanpassadictionaryasanargument.
Thecodesnippetbelowexplainsit.
deffunc(a=‘aa’,b=‘bb’,c=‘cc’,**keyargs):
…printa,b,c
…
>>>func()
aabbcc
>>func(**{‘a’:‘x’,‘b’:‘y’,‘c’:‘z’})
xyz
>>>
Here,theorderofparameterdoesnotmatter.
Advantages:
1. Weneednotremembertheorderofthearguments2. Wecanspecifyvaluestoonlythoseparameterswewantto
Variable-lengthargumentsarenotnamedinthefunctiondefinition.
Example3.2:Variable-lengtharguments
defadd(*numbers):
sum=0
fornumberinnumbers:
sum=sum+number
printsum
add(1,2,3,4,5)
add(2,4,6)
Thisallowsustoaddanynumberofvalues.
Anonymousfunctions
Functionsusingthelamdakeywordwithoutusing“def”keywordarecalled
anonymousfunctions.
Example3.3:Anonymousfunctions
sum=lamdaa,b:a+b
printsum(5,10)
Lamdaformscantakeanynumberofargumentsbutreturnjustonevalueintheformofanexpression.
Scopeofvariables
Thescopeofavariabledeterminestheportionoftheprogramwherewecanaccessaparticularvariable.
Globalscope:Avariablewithglobalscopecanbeusedanywhereintheprogramanditisdeclaredoutsideallfunctions/blocks.
Localscope:Whenavariableiscreatedinsidethefunction/block,thevariablebecomeslocaltoit.
Example3.4:Scope
x=10#globalvariable
defprintx():
y=5#localvariable
printx+y
printx
printx()
printy#NameError:name‘y’isnotdefined
Composition
Theactofjoining2ormorefunctionstogetheriscalledcomposition.
Example3.5
printmath.degrees(math.pi)
180.0
SolvedQuestions
1.DefineafunctiongetLargest(x,y)totakein2numbersandreturnthelargerofthem.
Ans:
defgetLargest(x,y):
ifx>y:
returnx
else:
returny
2.Writeapythonprogramtosimulateabasiccalculatorusingfunctionsforadd,subtract,multiplyanddivide.
Ans:
defadd(x,y):
return(x+y)
defsub(x,y):
return(x-y)
defmul(x,y):
return(x*y)
defdiv(x,y):
return(x/y)
#calculatorprogram
loop=1
#thisvariableholdstheuser’schoiceinthemenu:
choice=0
whileloop==1:
#MENU
print”Fourfunctioncalculator-chooseyouroption:”
print“1)Addition”,
print“2)Subtraction”,
print“3)Multiplication”,
print“4)Division”,
print“5)Quit”
choice=input(“Chooseyouroption:“)
ifchoice==1:
add1=input(”Firstnumber:“)
add2=input(”SecondNumber:“)
printadd1,“+”,add2,“=”,add(add1,add2)
elifchoice==2:
sub1=input(“Firstnumber:“)
sub2=input(“SecondNumber:“)
printsub1,“-”,sub2,“=”,sub(sub,sub2)
elifchoice==3:
mul1=input(“Firstnumber:“)
mul2=input(“SecondNumber:“)
printmul1,“*”,mul2,“=”,mul(mul1,mul2)
elifchoice==4:
div1=input(“Firstnumber:“)
div2=input(“SecondNumber:“)
printdiv1,“/”,div2,“=”,div(div1,div2)
elifchoice==5:
loop=0
print“Done!!”
Practiceproblems1. Defineafunction‘SubtractNumber(x,y)’whichtakesintwonumbersandreturnsthe
differenceofthetwo.2. Writeafunctioninpythontocalculatethepowerofagivennumber.Ifuserdoesn’t
specifytheexponentitshouldreturnthesquareofthenumber.
0.
Chapter4:Conditionalconstructsandlooping
Controlstructureschangetheorderthatstatementsareexecutedordecideifacertainstatementwillberun.
Conditionalconstructs
Whenaprogramhasmorethanonechoiceofactionsdependingonavariable’svalueitusesaconditionalconstruct.Decisionmakingstructuresrequirethattheprogrammerspecifiescondition(s)whichifdeterminedtobetrueasetofstatementsareexecutedandifevaluatedtofalseanothersetofstatementsareexecuted.
Construct Syntax Description
If ifcondition:
Statements
Iftheconditionistrue,thendotheindentedstatements.Iftheconditionisnottrue,thenskiptheindentedstatements.
if–else ifexpression:
statement(s)
else:
statement(s)
Inanif-elsestatementexactlyoneoftwopossibleindentedblocksisexecuted.
if–elif-else ifexpression1:
statement(s)
elifexpression2:
statement(s)
elifexpression3:
statement(s)
else:
statement(s)
Onlyiftheprecedingifstatementisfalse,thenextifstatementisexecuted.
Example4.1:Writeaprogramtoacceptelectricitybilldetails(i.e)customernumber,customername,previousmonthmeterreadingandcurrentmonthreadingandthenfindno.ofunitsconsumedbythecustomerandamountpayabletoelectricitydepartmentbyperformingfollowingchecks:-
First100unitscostperunitisRs.4.00
Next500unitscostperunitisRs.5.00
Beyond500unitscostperunitisRs.6.00
Step1:Firstlineofaprogramisacommentdetailingthepurposeoftheprogram
#Programtocalculateelectricitybill
Step2:Weneedtogettherequiredinputfromtheuser.
name=raw_input(“Entercustomer’sname:-”)
prev=float(raw_input(“\nEnterthepreviousmonth’sreading:-”))
curr=float(raw_input(“\nEnterthecurrentmonth’sreading:-”))
Step3:Calculatingthenumberofunitsofelectricityconsumed
#Consumedunitsiscurrentmeterreading-previousmeterreading
units=curr–prev
Step4:Decidingontheformulaforamountcalculation
ifunits<=100:
bill=units*4.00;
elifunits>100andunits<500:
bill=400+(units-100)*5.00;
else:
bill=400+2000+(units-500)*6.00;
Step5:Displayingtheoutput
print“No.ofunitsconsumed=“,units
print“Amountpayabletotheelectricitydepartment=Rs”,bill
Output:
Iterationstructures
Loopsareusedtorepeatedlyexecutethesamecodeinaprogram.Pythonhas2loops
for
while
for
Thegeneralsyntaxfor“for”loopis
foriteminsequence:
statement(s)
(or)
forvarinrange([start,]finish):
statement(s)
Therangefunctionusestwoargumentslikethisrange(start,finish).startisthefirstnumberthatisproduced.finishisonelargerthanthelastnumber.
Example4.2:Writeaprogramtoprintnumbersfrom0to10.
forainrange(0,10):
print(a)
Theoutputis
0123456789
Thebreakstatementbreaksoutofthesmallestenclosingfororwhileloop.Itcanbeusedtounconditionallyjumpoutoftheloop.Itterminatestheexecutionoftheloop.
Loopstatementsmayhaveanelseclause;itisexecutedwhentheloopterminatesthroughexhaustionofthelist(withfor)orwhentheconditionbecomesfalse(withwhile),
butnotwhentheloopisterminatedbyabreakstatement.ThiscanbeexplainedwithExample3.
Example4.3:Writeaprogramtoprintallprimenumbersfrom2to50usingforloop.
Weneedtodivideeachnumberbyallnumbersstartingfrom2toitself.So,ifwetake7,weneedtodivide7by2,3,4,5and6andifit’snotdivisiblebyanyofthesenumbers,thenweconcludethatit’saprimenumberandweprintitontheoutputscreen.
forninrange(2,50):
x_range=range(2,n)
forxinx_range:
ifn%x==0:
break
else:
#loopfellthroughwithoutfindingafactor
print(n)
Programflow:
Let’staken=9
x_range=range(2,9)
forxinx_range:
if9%x==0:
break
else:
#loopfellthroughwithoutfindingafactor
print(9)
Whenx=2
If9%2==0 � falsesocontinuetheforloop
If9%3==0 � truesobreakoutoftheloopnoneedtocheckotherfactors.9isnotaprimenumber.
while
Thesyntaxofthewhileloopisgivenbelow
whilecondition:
statement(s)
Thewhileloopisusedincaseswhenthestartorendofaniterationisnotknown.
Example4.4:WriteaprogramforprintingFibonacciseries.
#Fibonacciseries:
#thesumoftwoelementsdefinesthenextnumber
a,b=0,1
whileb<10:
…printb
…a,b=b,a+b
1
1
2
3
5
8
•Thefirstlinecontainsamultipleassignment:thevariablesaandbsimultaneouslygetthenewvalues0and1.Onthelastlinethisisusedagain,demonstratingthattheexpressionsontheright-handsideareallevaluated
firstbeforeanyoftheassignmentstakeplace.Theright-handsideexpressionsareevaluatedfromthelefttotheright.
•Thewhileloopexecutesaslongasthecondition(here:b<10)remainstrue.InPythonanynonzerointegervalueistrue;zeroisfalse.Theconditionmayalsobeastringorlistvalue,infactanysequence;anythingwithanon-zerolengthistrue,emptysequencesarefalse.Thetestusedintheexampleisasimplecomparison.
•Thebodyoftheloopisindented:indentationisPython’swayofgroupingstatements.
Atrailingcommaavoidsthenewlineaftertheoutput.
a,b=0,1
whileb<100:
printb,
a,b=b,a+b
Nowtheoutputwouldbe
1123581321345589
Note:Everythingthatcanbedonewithforloopscanalsobedonewithwhileloopsbutforloopsgiveaneasywaytogothroughalltheelementsinalistortodosomethingacertainnumberoftimes.
ThecontinuestatementisusedtotellPythontoskiptherestofthestatementsinthecurrentloopblockandtocontinuetothenextiterationoftheloop.Continuewillreturnbackthecontroltothebeginningoftheloop.
passdoesnothingbutmaybeusedasaplaceholderforfutureimplementation.
SolvedPrograms1. Writeaprogramtovalidatepasswordlength.
Ans:
#Thisprogramgetsanewpasswordfromtheuservalidatesitslengthand
#printsanerrormessageifthepasswordenteredislessthan6characters
whileTrue:
s=raw_input(‘Enternewpassword:‘)
iflen(s)<6:
print‘Inputisofinsufficientlength’
continue
else:
print“Passwordchangedsuccessfully”
break
2. Writeaprogramtoaddnumbersarbitrarilytilltheuserenters0.
Ans:
a=1
s=0
print(‘EnterNumberstoaddtothesum.’)
print(‘Enter0toquit.’)
whilea!=0:
a=int(raw_input(‘Number?‘))
s+=a
print‘TotalSum=‘,s
3. WriteaprograminPythontofindthesummationofthefollowingseriesusingforloops.
1+x+x2+x3+…+xn
Ans:
importmath
sum=0
n=int(raw_input(“Enterthevalueofn:”))
x=int(raw_input(“Enterthevalueofx:”))
foriinrange(10):
sum=sum+pow(x,i);
print”1+“,x,“+“,x,“^2+“,x,“^3+…”,x,“^”,n,”=”,sum,“\n”;
raw_input()
4. WriteaprograminPythontoconvertagivennumberfromDecimaltoBinary.
Ans:
i=1
s=0
dec=int(raw_input(“Enterthedecimaltobeconverted:”))
whiledec>0:
rem=dec%2
s=s+(i*rem)
dec=dec/2
i=i*10
print“Thebinaryofthegivennumberis:”,s
raw_input()
5.Writeprogramtoinputanynumberandtoprintallfactorsofthatnumber.
Ans.
n=input(“Enterthenumber”)
foriinrange(2,n):
ifn%i==0:
printi,“isafactorof”,n
6.WriteaprogramtoinputanynumberandtocheckwhethergivennumberisArmstrongornot.(Armstrong1,153,etc.13=1,13+53+33=153)
Ans.
n=input(“Enterthenumber”)
savedn=n
sum=0
whilen>0:
a=n%10
sum=sum+a*a*a
n=n/10
ifsavedn==sum:
printsavedn,“isanArmstrongNumber”
else:
printsavedn,“isnotanArmstrongNumber”
7.Writeaprogramtofindallprimenumbersuptogivennumber.
Ans.
n=input(“Enterthenumber”)
i=2
flag=0
while(i<n):
if(n%i)==0:
flag=1
printn,“iscomposite”
break
i=i+1
ifflag==0:printn,“isprime”
8.Writeaprogramtofindthesumofalldigitsofthegivennumber.
Ans.
n=input(“Enterthenumber”)
rev=0
while(n>0):
a=n%10
sum=sum+a
n=n/10
print“Sumofdigits=”,sum
9.Writeaprogramtofindthereverseofanumber.
Ans.
n=input(“Enterthenumber”)
rev=0
while(n>0):
a=n%10
rev=(rev*10)+a
n=n/10
print“Reversednumber=”,rev
10.Writeaprogramtoprintthepyramid.
1
22
333
4444
55555
Ans.
foriinrange(1,6):
forjinrange(1,i+1):
printi,
PracticeProblems1.Writeaprogramtofindtherootsofaquadraticequation.
2. Writeaprogramtoacceptelectricitybilldetails(i.e)customernumber,customername,previousmonthmeterreadingandcurrentmonthreadingandthenfindno.ofunitsconsumedbythecustomerandamountpayabletoelectricitydepartmentbyperformingfollowingchecks:-
First100unitscostperunitisRs.4.00
Next500unitscostperunitisRs.5.00
Beyond500unitscostperunitisRs.6.00
3. WriteaprograminPythontofindthesummationofthefollowingseriesusingforloops.
1-x+x2/2!-x3/3!+…+(-1)nxn/n!
4. Writeaprogramtosimulateaguessingnumbergame.Generateanumberfrom1to100andasktheusertoguessitcorrectlywithin5tries.Aftereachguess,theprogrammusttellwhetherthenumberishigherthan,lowerthan,orequaltoyourguess.
5.Writeaprogramtoprinteveryintegerbetween1andndivisiblebym.6.Whatdoesthefollowingprintout?
foriinrange(1,10):
forjinrange(1,10):
printi*j,
7.Writeaprogramtoprintthepyramid.
1
12
123
1234
12345
Chapter5:Strings
StringsareamongstthemostpopulartypesinPython.Wecancreatethemsimplybyenclosingcharactersinquotes.Pythontreatssinglequotesthesameasdoublequotes.
Creatingstringsisassimpleasassigningavaluetoavariable.Forexample:
str1=‘HelloWorld!’
str2=“PythonProgramming”
AccessingValuesinStrings
Pythondoesnot support a character type; these are treated as stringsof lengthone,thus also considered a substring. To access substrings, we use the square brackets forslicing along with the index or indices to obtain our substring. Following is a simpleexample:
str1=‘HelloWorld!’
str2=“PythonProgramming”
print“str1[0]:“,str1[0]
print“str2[7:11]:“,str2[7:11]
Whentheabovecodeisexecuted,itproducesthefollowingresult:
Fig5.1:Accessingstringsoutputscreenshot
UpdatingStrings
Wecan“update”anexistingstringby(re)assigningavariable toanotherstring.Thenewvaluecanberelatedtoitspreviousvalueortoacompletelydifferentstringaltogether.Followingisasimpleexample:
str1=‘HelloWorld!’
str2=str1[:6]+‘Python’
print“UpdatedString:-“,str2
Whentheabovecodeisexecuted,itproducesthefollowingresult:
Fig5.2:Updatingstrings
EscapeCharacters
Followingtableisalistofescapeornon-printablecharactersthatcanberepresentedwithbackslashnotation.
An escape character gets interpreted; in a single quoted as well as double quotedstrings.
Backslashnotation
Description
\a Belloralert
\b Backspace
\cx Control-x
\C-x Control-x
\e Escape
\f Formfeed
\M-\C-x Meta-Control-x
\n Newline
\nnn Octalnotation,wherenisintherange0.7
\r Carriagereturn
\s Space
\t Tab
\v Verticaltab
\x Characterx
\xnn Hexadecimalnotation,wherenisintherange0.9,a.f,orA.F
Table5.1:Escapecharacters
StringSpecialOperators
Assumestringvariableaholds‘Hello’andvariablebholds‘Python’,then:
Operator Description Example
+ Concatenation-Addsvaluesoneithersideoftheoperator
a+bresultsinHelloPython
* Repetition-Createsnewstrings,concatenating
a*2resultsinHelloHello
multiplecopiesofthesamestring
[] Slice-Givesthecharacterfromthegivenindex
a[1]resultsine
[:] RangeSlice-Givesthecharactersfromthegivenrange
a[1:4]resultsinell
In Membership-Returnstrueifacharacterexistsinthegivenstring
Hinaresultsin1
notin Membership-Returnstrueifacharacterdoesnotexistinthegivenstring
Mnotinaresultsin1
r/R RawString-SuppressesactualmeaningofEscapecharacters.Thesyntaxforrawstringsisexactlythesameasfornormalstringswiththeexceptionoftherawstringoperator,theletter“r,”whichprecedesthequotationmarks.The“r”canbelowercase(r)oruppercase(R)andmustbeplacedimmediatelyprecedingthefirstquotemark.
printr’\n’prints\nandprintR’\n’prints\n
% Format-PerformsStringformatting
Table5.2:StringSpecialOperators
StringFormattingOperator
OneofPython’scoolestfeaturesisthestringformatoperator%.ThisoperatorisuniquetostringsandmakesupforthepackofhavingfunctionsfromC’sprintf()family.Followingisasimpleexample:
print“Mynameis%sandweightis%dkg!”%(‘Tara’,50)
Whentheabovecodeisexecuted,itproducesthefollowingresult:
Fig5.3:formattingusing%
Hereisthelistofcompletesetofsymbolswhichcanbeusedalongwith%:
FormatSymbol
Conversion
%c Character
%s stringconversionviastr()priortoformatting
%i signeddecimalinteger
%d signeddecimalinteger
%u unsigneddecimalinteger
%o octalinteger
%x hexadecimalinteger(lowercaseletters)
%X hexadecimalinteger(UPPERcaseletters)
%e exponentialnotation(withlowercase‘e’)
%E exponentialnotation(withUPPERcase‘E’)
%f floatingpointrealnumber
%g theshorterof%fand%e
%G theshorterof%fand%E
Table5.3:formatsymbols
Built-instringfunctions
Pythonincludesthefollowingbuilt-inmethodstomanipulatestrings:
SNo Methods Description Example
1 capitalize()
Capitalizesfirstletterofstring
str=“hellopython“
printstr.capitalize()
Hellopython
2 endswith(suffix,beg=0,end=len(string))
Determinesifstringorasubstringofstring(ifstartingindexbegandendingindexendaregiven)endswithsuffix;
Computer”.endswith(“er”)
True
returnstrueifsoandfalseotherwise
3 find(str,beg=0end=len(string))
Determineifstroccursinstringorinasubstringofstringifstartingindexbegandendingindexendaregivenreturnsindexiffoundand-1otherwise
str=‘Computer’
printstr.find(‘put’)
>>3
#Onomittingthestartparameters,thefunctionstartsthesearchfrom
#thebeginning.
printstr.find(‘put’,2)
>>3
printstr.find(‘put’,1,3)
>>-1
#Displays-1becausethesubstringcouldnotbefoundbetweentheindex1and3-1
4 index(str,beg=0,end=len(string))
Sameasfind(),butraisesanexceptionifstrnotfound
“Computer”.index(‘pat’)
Traceback(mostrecentcalllast):
File“<pyshell#1>”,line1,in<module>
“Computer”.index(‘pat’)
ValueError:substringnotfound
5 isalnum()
Returnstrueifstringhasatleast1characterandallcharactersarealphanumericandfalse
str=‘HelloPython’
printstr.isalnum()
False
#ThefunctionreturnsFalseasspaceisanalphanumericcharacter.
otherwise print“Python123”.isalnum()
True
6 isalpha()
Returnstrueifstringhasatleast1characterandallcharactersarealphabeticandfalseotherwise
print‘Python123’.isalpha()
False
print‘python’.isalpha()
True
7 isdigit()
Returnstrueifstringcontainsonlydigitsandfalseotherwise
str=‘1234’
printstr.isdigit()
True
8 islower()
Returnstrueifstringhasatleast1casedcharacterandallcasedcharactersareinlowercaseandfalseotherwise
print‘HELLOpython’.islower()
hellopython
9 isnumeric()
Returnstrueifaunicodestringcontainsonlynumericcharactersandfalseotherwise
str=u”year2013”
printstr.isnumeric()
False
10 isspace()
Returnstrueifstringcontainsonlywhitespace
str=’‘
printstr.isspace()
True
charactersandfalseotherwise
11 istitle()
Returnstrueifstringisproperly“titlecased”andfalseotherwise
print‘HelloWorld’.istitle()
True
12 isupper()
Returnstrueifstringhasatleastonecasedcharacterandallcasedcharactersareinuppercaseandfalseotherwise
print“‘HELLOpython’.isupper()
True
13 join(seq)
Merges(concatenates)thestringrepresentationsofelementsinsequenceseqintoastring,withseparatorstring
str1=(‘10’,‘oct’,‘2013’)
str=”-”
printstr.join(str1)
10-oct-2013
14 len(string)
Returnsthelengthofthestring
len(“Computer”)
8
15 lower()
Convertsalluppercaselettersinstringtolowercase
“OpticalFibre”.lower()
‘opticalfibre’
16 lstrip()
Removesallleadingwhitespaceinstring
”Python“.lstrip()
‘Python‘
17 max(str)
Returnsthemaxalphabeticalcharacterfromthestringstr
max(“Python”)
‘y’
18 min(str)
Returnstheminalphabeticalcharacterfromthestringstr
min(“Python”)
‘P’
19 replace(old,new[,max])
Replacesalloccurrencesofoldinstringwithneworatmostmaxoccurrencesifmaxgiven
“C++isapowerfullanguage”.replace(“C++”,“Python”)
‘Pythonisapowerfullanguage’
20 rfind(str,beg=0,end=len(string))
Sameasfind(),butsearchbackwardsinstring
“PythonProgram”.rfind(“P”)
7
21 rindex(str,beg=0,end=len(string))
Sameasindex(),butsearchbackwardsinstring
“PythonProgram”.rindex(“P”)
7
22 rstrip()
Removesalltrailingwhitespaceofstring
”Python“.rstrip()
‘Python’
23 split(str=””,num=string.count(str))
Splitsstringaccordingtodelimiterstr(spaceifnotprovided)andreturnslistofsubstrings;splitintoatmostnumsubstringsifgiven
“1:Anand-2:Babu-3:Charles-4:Dravid”.split(‘-‘)
[‘1:Anand’,‘2:Babu’,‘3:Charles’,‘4:Dravid’]
24 splitlines(num=string.count(‘\n’))
Splitsstringatall(ornum)NEWLINEsandreturnsalistofeachlinewithNEWLINEsremoved
“1:Anu-\n2:Banu-\n3:Charles-\n4:David”.splitlines(3)
[‘1:Anu-\n’,‘2:Banu-\n’,‘3:Charles-\n’,‘4:David’]
25 startswith(str,beg=0,end=len(string))
Determinesifstringorasubstringofstring(ifstartingindexbegandendingindexendaregiven)startswithsubstringstr;returnstrueifsoandfalse
“Pythonisafreesoftware…….”.startswith(“Python”)
True
otherwise
26 strip([chars])
Performsbothlstrip()andrstrip()onstring
“Python“.strip()
‘Python’
27 swapcase()
Invertscaseforalllettersinstring
“pythonPROGRAMMING”.swapcase()
‘PYTHONprogramming’
28 title()
Returns“titlecased”versionofstring,thatis,allwordsbeginwithuppercaseandtherestarelowercase
“pythonPROGRAMMING”.title()
‘PythonProgramming’
29 upper()
Convertslowercaselettersinstringtouppercase
“python”.upper()
‘PYTHON’
30 zfill(width)
Returnsoriginalstringleftpaddedwithzerostoatotalofwidthcharacters;intendedfornumbers,zfill()retainsanysigngiven(lessone
“1234”.zfill(10)
‘0000001234’
zero)
Table5.4:Built-instringfunctions
Stringconstants
Constant Description Example
string.ascii_uppercase
Thecommanddisplaysastringcontaininguppercasecharacters.
>>>string.ascii_uppercase
‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’
string.ascii_lowercase
Thecommanddisplaysastringcontainingalllowercasecharacters.
>>>string.ascii_lowercase
‘abcdefghijklmnopqrstuvwxyz’
string.ascii_letters
Thecommanddisplaysastringcontainingbothuppercaseandlowercasecharacters.
>>>string.ascii_letters
‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’
string.digits
Thecommanddisplaysastringcontainingdigits.
>>>string.digits
‘0123456789’
string.hexdigits
Thecommanddisplaysastringcontaininghexadecimalcharacters.
>>>string.hexdigits
‘0123456789abcdefABCDEF’
string.octdigits
Thecommanddisplaysastringcontainingoctalcharacters
>>>string.octdigits
‘01234567’
string.punctuations
Thecommanddisplaysastringcontainingallthepunctuationcharacters.
>>>string.punctuations
‘!”#$%&'()*+,-./:;<=>?@[\]^_`{|}-‘
string.whitespace
ThecommanddisplaysastringcontainingallASCIIcharactersthatareconsidered
whitespace.Thisincludesthecharactersspace,tab,linefeed,return,formfeed,andverticaltab.
>>>string.whitespace
‘\t\n\x0b\x0c\r‘
string.printable
Thecommanddisplaysastringcontainingallcharacterswhichare
>>>string.printable
‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!
“#$%&'()*+,-./:;<=>?@[\]^_`{|}-\t\n\r\x0b\x0c’
consideredprintablelikeletters,digits,punctuationsandwhitespaces.
Table5.6:stringconstants
Example5.1:Writeaprogramtocheckwhetherthestringisapalindromeornot.
defpalin():
str=input(“EntertheString”)
l=len(str)
p=l-1
index=0
while(index<p):
if(str[index]==str[p]):
index=index+1
p=p-1
else:
print“Stringisnotapalindrome”
break
else:
print“StringisaPalindrome”
Executionsteps:
Fig5.4:Palindromeexecutionsteps
Output:
StringisaPalidrome
RegularexpressionsandPatternmatching
Aregularexpressionisasequenceoflettersandsomespecialcharacters(alsocalledmetacharacters).Thesespecialcharactershavesymbolicmeaning.Thesequenceformedbyusingmetacharactersandletterscanbeusedtorepresentagroupofpatterns.
Regularexpressionscanbeusedinpythonformatchingaparticularpatternbyimportingtheremodule.
Note:remoduleincludesfunctionsforworkingonregularexpression.
Thefollowingtableexplainshowthemetacharactersareusedtoformregularexpressions.
S.No MetaCharacter Usage Example
1 [] Usedtomatchasetofcharacters
[star]
Theregularexpression
wouldmatchanyofthe
characterss,t,aorr.
[a-z]
Theregularexpression
wouldmatchonly
lowercasecharacters.
2 ^ Usedtocomplementingasetofcharacters
[^star]
Theregularexpression
wouldmatchanyother
charactersthans,t,aorr.
3 $ Usedtomatchtheendofstringonly
Star$
Theregularexpression
wouldmatchStarin
BlueStarbutwillnotmatch
StarinStardom
4 * Usedtospecifythatthepreviouscharactercanbematchedzeroormoretimes.
B*e
Theregularexpression
wouldmatchstringslike
Bye,Blue,Beeandsoon.
5 + Usedtospecifythatthepreviouscharactercanbematchedoneormoretimes.
B+r
TheregularexpressionwouldmatchstringslikeBeer,Baarandsoon.
6 ? Usedtospecifythatthepreviouscharactercanbematchedeither
onceorzerotimes
B?ar
TheregularexpressionwouldonlymatchstringslikeBarorBear
7 {} Thecurlybracketsaccepttwointegervalues.Thefirstvalue
specifiestheminimumnoofoccurrencesandsecondvaluespecifiesthemaximumof
occurrences
wate{1,4}r
Theregularexpression
wouldmatchonlystrings
water,wateer,wateeeror
wateeeer
Table5.7:metacharacters
Functionsfromremodule
Function Description
re.compile()
compilethepatternintopatternobjects.Afterthecompilationthepatternobjectswillbeabletoaccessmethodsforvariousoperationslikesearchingandsubstitutions
re.match()
Thematchfunctionisusedtodetermineiftheregularexpression(RE)matchesatthebeginningofthestring.
re.group()
ThegroupfunctionisusedtoreturnthestringmatchedtheRE
re.start()
Thestartfunctionreturnsthestartingpositionofthematch.
re.end()
Theendfunctionreturnstheendpositionofthematch.
re.span()
Thespanfunctionreturnsthetuplecontainingthe(start,end)positionsofthematch
re.search()
ThesearchfunctiontraversesthroughthestringanddeterminesthepositionwheretheREmatchesthestring
re.findall()
ThefunctiondeterminesallsubstringswheretheREmatches,andreturnsthemasalist.
re.finditer()
ThefunctiondeterminesallsubstringswheretheREmatches,andreturnsthemasaniterator.
Table5.8:functionsinremodule
Example5.2:Demonstrationofrefunctions
importre
P=re.compile(“hell*o”)
m=re.match(“hell*o”,“hellooooopython”)
printm.group()
m=re.match(‘hell*o’,‘hellooooopython’)
printm.start()
m=re.match(‘hell*o’,‘hellooooopython’)
printm.end()
m=re.match(‘hell*o’,‘hellooooopython’)
printm.span()
m=re.search(‘hell*o’,‘hellooopython’)
printm
m=re.findall(‘hell*o’,‘hellohelloopython’)
printm
SolvedPrograms1. Writeaprogramtocountnoof‘s’inthestring‘mississippi’.
Ans:
deflettercount():
word=‘mississippi’
count=0
forletterinword:
ifletter==‘s’:
count=count+1
print(count)
2. Writeaprogramthatreadsastringanddisplaythelongestsubstringofthegivenstringhavingjusttheconsonants.
Ans:
string=raw_input(‘‘Enterastring:’’)
length=len(string)
maxlength=0
maxsub=‘’
sub=‘’
lensub=0
forainrange(length):
ifstring[a]in‘aeiou‘orstring[a]in‘AEIOU’:
iflensub>maxlength:
maxsub=sub
maxlength=lensub
sub=‘’
lensub=0
else:
sub+=string[a]
lensub=len(sub)
a+=1
print‘‘Maximumlengthconsonentsubstringis:’’,maxsub,
print‘‘with’’,maxlength,‘‘characters’’
3.Writeaprogramtodetermineifthegivensubstringispresentinthestring.
importre
substring=‘Rain’
search1=re.search(substring,‘RainRaingoaway!’)
ifsearch1:
position=search1.start()
print“matched”,substring,“atposition”,position
else:
print“Nomatchfound”
4.Writeaprogramtodetermineifthegivensubstring(definedusingmetacharacters)ispresentinthegivenstring
Ans:
importre
p=re.compile(‘dance+’)
search1=re.search(p,‘WesterndancersdanceforEnglishmusicwell’)
ifsearch1:
match=search1.group()
print“matched=”,match
index=search1.start()
print“atposition”,index
else:
print“Nomatchfound”
5.WritePythonscriptthattakesastringwithmultiplewordsandthencapitalizesthefirstletterofeachwordandformsanewstringoutofit.
Ans.
string=raw_input(‘‘Enterastring:’’)
length=len(string)
a=0
end=length
string2=‘’#emptystring
whilea<length
ifa==0
string2+=string[0].upper()a+=1
elif(string[a]==‘’andstring[a+1)!=‘’):
string2+=string[a]
string2+=string[a+1].upper()a+=2
else:
string2+=string[a]
a+=1
print‘‘Originalstring:’’,string
print‘‘Convertedstring:’’,string2
6.Whichstringmethodisusedtoimplementthefollowing?
a)Tocountthenumberofcharactersinthestring.
b)Tochangethefirstcharacterofthestringincapitalletter.
c)Tocheckwhethergivencharacterisletteroranumber.
d)Tochangelowercasetouppercaseletter.
e)Changeonecharacterintoanothercharacter.
Ans.
a)len(str)
b)str.title()orstr.capitalize()
c)str.isalphaandstr.isdigit()
d)lower(str[i])
e)str.replace(char,newchar)
7.Writeaprogramtoinputanystringandtofindnumberofwordsinthestring.
Ans.
str=“Honestyisthebestpolicy”
words=str.split()
printlen(words)
8.Considerthestringstr=”AFriendIndeed”.WritestatementsinPythontoimplementthefollowing
a)Todisplaythelastfourcharacters.
b)Todisplaythesubstringstartingfromindex4andendingatindex8.
c)Tocheckwhetherstringhasalphanumericcharactersornot.
d)Totrimthelastfourcharactersfromthestring.
e)Totrimthefirstfourcharactersfromthestring.
f)Todisplaythestartingindexforthesubstring“end”.
g)Tochangethecaseofthegivenstring.
h)Tocheckifthestringisintitlecase.
i)Toreplacealltheoccurrencesofletter‘e’inthestringwith‘*’?
Ans:
a)str[-4:]
b)str[4:8]
c)str.isalnum()
d)str=str[4:]
e)str=str[-4:]
f)str.find(“end”)
g)str.swapcase()
h)str.istitle()
i)str.replace(‘e’,’*’)
PracticeProblems
1.WriteaprograminPythontocountthenumberofvowelsinagivenword.
2.WriteaprogramusingregularexpressionsinPythontovalidatepasswordsinagivenlistofpasswords.
3.Writeaprogramtopartitionthestringattheoccurrenceofagivenletter.
4.WriteaprograminPythontosortagivenarrayofstudentnamesinalphabeticalorder.
5.Considerthestringstr=”HelloPython”.Writestatementsinpythontoimplementthefollowing
a)Todisplaythelastsixcharacters.
b)Todisplaythesubstringstartingfromindex2andendingatindex6
c)Tocheckwhetherstringhasalphanumericcharactersornot.
d)Totrimthelastsixcharactersfromthestring.
e)Totrimthefirstsixcharactersfromthestring.
f)Tochangethecaseofthegivenstring.
g)Tocheckifthestringisintitlecase.
Chapter6:Lists
ListsarethesimplestdatastructureinPythonandareusedtostorealistofvalues.Listsarecollectionsofitems(strings,integers,orevenotherlists).Eachiteminthelisthasanassignedindexvalue.Listsareenclosedin[].Eachiteminalistisseparatedbyacomma.Unlikestrings,listsaremutable,whichmeanstheycanbechanged.
Listoperations
Function Description Example
Creation
Listsarecreatedusingacommaseparatedlistofvaluessurroundedbysquarebrackets.Listsholdasequenceofvalues.Listsareveryeasytocreate,thesearesomeofthewaystomakelists.
L=[]#Anemptylistiscreatedusingonlysquarebrackets
list1=[‘one’,‘two’,‘three’,‘four’,‘five’]
numlist=[1,2,3,4,5]
Length
Withthelengthfunctionwecangetthelengthofalist
list=[“1”,“hello”,2,“world”]
len(list)
4
Append
Listappendwilladdtheitemattheend.list.append(x)willaddanelementtotheendofthelist
list=[‘Python’,‘Java’,‘C++’]
list.append(‘C’)
printlist
[‘Python’,‘Java’,‘C++’,‘C’]
Insert
Ifwewanttoaddatthebeginningormiddle,wecanusetheinsertfunction.
list.insert(0,“HTML”)
printlist
[‘HTML’,‘Python’,‘Java’,‘C++’,‘C’]
list.insert(3,“VB”)
printlist
[‘HTML’,‘Python’,‘Java’,‘VB’,‘C++’,‘C’]
Remove
Toremoveanelement’sfirstoccurrenceinalist,simplyuselist.remove.Thesyntaxis:list.remove(x).xcanbetheitemname.xcanalsobeanumber.
list=[‘HTML’,‘Python’,‘Java’,‘VB’,‘C++’,‘C’]
list.remove(“Java”)
printlist
[‘HTML’,‘Python’,‘VB’,‘C++’,‘C’]
list=[1,2,3,4]
list.remove(2)
printlist
[1,3,4]
Delete
Weusedeltoremoveitembasedonindexposition.
list=[‘HTML’,‘Python’,‘Java’,‘VB’,‘C++’,‘C’]
dellist[1]
printlist
HTML,Java,VB,C++,C
Extend
Itjoinsalistwithanother list2=[“Javascript”,“VBScript”]
list.extend(list2)
printlist
[‘HTML’,‘VB’,‘C++’,‘C’,‘Javascript’,‘VBScript’]
In Thekeyword“in”canbeusedtotestifanitemisinalist.
list=[“red”,“orange”,“green”,“blue”]
if“red”inlist:
print“redispresentinlist”
redispresentinlist
Notin
Keyword“not”canbecombinedwith“in”.
list=[“red”,“orange”,“green”,“blue”]
if“purple”notinlist:
print“purplenotinlist”
purplenotinlist
Reverse
Thereversemethodreversestheorderoftheentirelist.
#Toprintareverselist
L=[10,20,40]
foriinlist[::-1]:
printi
#OR
L.reverse()
printL
[40,20,10]
Sorting
Ittakesalistandreturnsanewlistwiththoseelementsinsortedorder.Theoriginallistisnotchanged.Thesorted()functioncanbecustomizedthoughoptionalarguments.Thesorted()optionalargumentreverse=True,e.g.sorted(list,reverse=True),makesitsortbackwards.
#createalistwithsomenumbersinit
numbers=[5,1,4,3,2,6,7,9]
#printsthenumberssorted
printsorted(numbers)
#theoriginallistofnumbersarenotchanged
printnumbers
[1,2,3,4,5,6,7,9]
Split
Spliteachelementinalist
list=‘one,two,three,four,five’
newlist=list.split(‘,’)
printnewlist
[‘one’,‘two’,‘three’,‘four’,‘five’]
Indexing
Eachiteminthelisthasanassignedindexvaluestartingfrom0.Accessingelementsinalistiscalledindexing.
list=[“apple”,“banana”,“mango”]
list[0]==“apple”
list[1]==“banana”
list[2]==“mango”
Slicing
Accessingpartsofsegmentsiscalledslicing.Listscanbeaccessedjustlikestringsbyusingthe[]operators.Thekeypointtorememberisthatthe:endvaluerepresentsthefirstvaluethatisnotintheselectedslice.So,thedifferencebetweenendandstartisthenumberofelementsselected(ifstepis1,thedefault).
Let’screatealistwithsomevaluesinit
colors=[‘yellow’,‘red’,‘blue’,‘green’,‘black’]
printcolors[0]
Yellow
printcolors[1:]
red,blue,green,black
a[start:end]#itemsstartthroughend-1
a[start:]#itemsstartthroughtherestofthearray
a[:end]#itemsfromthebeginningthroughend-1
a[:]#acopyofthewholearray
Thereisalsothestepvalue,whichcanbeusedwithanyoftheabove
a[start:end:step]#startthroughnotpastend,bystep
Negativeindexing
Theotherfeatureisthatstartorendmaybeanegativenumber,whichmeansitcountsfromtheendofthearrayinsteadofthebeginning.
a[-1]#lastiteminthearray
a[-2:]#lasttwoitemsinthearray
a[:-2]#everythingexceptthelasttwoitems
Callstolistmethodshavethelisttheyoperateonappearbeforethemethodname.Anyothervaluesthemethodneedstodoitsjobisprovidedinthenormalwayasanextraargumentinsidetheroundbrackets.
Thefollowingfigurehelpstodemonstratenegativeindices
Listfunctions
S.No Function Description
1 cmp(list1,list2) Compareselementsofbothlists.
2 len(list) Givesthetotallengthofthelist.
3 max(list) Returnsitemfromthelistwithmaxvalue.
4 min(list) Returnsitemfromthelistwithminvalue.
5 list(seq) Convertsatupleintolist.
6 list.append(obj) Appendsobjectobjtolist
7 list.count(obj) Returnscountofhowmanytimesobjoccursinlist
8 list.extend(seq) Appendsthecontentsofseqtolist
9 list.index(obj) Returnsthelowestindexinlistthatobjappears
10 list.insert(index,obj) Insertsobjectobjintolistatoffsetindex
11 list.pop(obj=list[-1]) Removesandreturnslastobjectorobjfromlist
12 list.remove(obj) Removesobjectobjfromlist
13 list.reverse() Reversesobjectsoflistinplace
14 list.sort([func]) Sortsobjectsoflist,usecomparefuncifgiven
Table6.1:Summaryoflistfunctionsandmethods
Matrices
Amatrixisagrid,witheachlocationinthegridcontainingsomeinformation.Considertheexcelsheet.Amatrixhasrowsandcolumnsandeachelementisinsideacell.Touniquelyidentifytheelementweusetherownameandcolumnname.
Fig6.1:Matrix–excel
Toaccess“2”,wesayB1inSpreadsheet,whereBisthecolumnheaderand1istherow.Inacomputer,westorethematrixandaccesstheelementsusingindices.
0 1 2
0 1 2 3
1 4 5 6
Fig6.2:Matrix–2DArray
Toaccess“2”,wesay[0][1].
Matriximplementationusinglist
Wecanimplementmatrixoperationusinglist.Matrixoperationcanbeimplementedusingnestedlist.Listinsideanotherlistiscallednestedlist.
Asafirststep,weneedtogetthenumberofrowsandcolumns.
m=int(raw_input(“Entertotalnumberofrows”))
n=int(raw_input(“Entertotalnumberofcolumns”))
Afterthatwecancreateamatrixnameda,asstatedbelow.
a=[[random.random()forrowinrange(m1)]forcolin
range(n1)]
Weneedtoimportrandomfile.Thisstepgeneratesamatrixliketheonelistedbelowifweentervaluesfornumberofrowsandcolumnsas2.Itisalsofilledwithsomerandomvaluesasshowninfigbelow.
0.314 0.678
0.191 0.567
Fig6.3:List-Initialstate
Wecanfillthematrixwithvaluesfromtheuser.
foriinrange(m):
forjinrange(n):
l[k]=int(raw_input((“Enterelement”)))
1 2
3 4
Fig6.4:List-withvalues
Finally,wecanprintthevalueswiththebelowcode.
foriinrange(m):
forjinrange(n):
printl[k],‘\t’,
k=k+1
Example6.1:WriteaprogramtoinputanymatrixwithmXn,andprintthenumberontheoutputscreeninmatrixformat.
m=int(raw_input(“Entertotalnumberofrows”))
n=int(raw_input(“Entertotalnumberofcolumns”))
l=range(m*n)
k=0
print“Inputallmatrixelementsoneafterother”
foriinrange(m):
forjinrange(n):
l[k]=int(raw_input((“Enternewelement”)))
k=k+1
print“outputis”
k=0
foriinrange(m):
forjinrange(n):
printl[k],‘\t’,
k=k+1
SolvedQuestions1. Writeaprogramtouselistfunctionstosortalistandfindthemaximumand
minimummarksinaclass.
Ans:
print“EnterNumberofMarks:“,
maxrange=0
maxrange=input()
i=0
marks=[]
foriinrange(0,maxrange):
marks.append(input())
#Sortthemarks
marks.sort()
foriinrange(0,maxrange):
printmarks[i]
print“Highestscoreis”,max(marks)
print“Lowestscoreis”,min(marks)
print“ClassAverageis”,sum(marks)/maxrange
2. Writeaprogramtoinputanytwomatricesandprintsumofmatrices.
Ans:
importrandom
m1=int(raw_input(“Entertotalnumberofrowsinthefirstmatrix”))
n1=int(raw_input(“Entertotalnumberofcolumnsinthefirstmatrix”))
a=[[random.random()forrowinrange(m1)]forcolinrange(n1)]
foriinrange(m1):
forjinrange(n1):
a[i][j]=int(raw_input(“?“))
m2=int(raw_input(“Entertotalnumberofrowsinthefirstmatrix”))
n2=int(raw_input(“Entertotalnumberofcolumnsinthefirstmatrix”))
b=[[random.random()forrowinrange(m2)]forcolinrange(n2)]
foriinrange(m2):
forjinrange(n2):
b[i][j]=int(raw_input(“?“))
c=[[random.random()forrowinrange(m1)]forcolinrange(n1)]
if((m1==m2)and(n1==n2)):
print“outputis”
foriinrange(m1):
forjinrange(n1):
c[i][j]=a[i][j]+b[i][j]
printc[i][j],‘\t’,
else:
print“Matrixadditionnotpossible”
3.Writeaprogramtoinputanytwomatricesandprintproductofmatrices.
importrandom
m1=int(raw_input(“Entertotalnumberofrowsinthefirstmatrix”))
n1=int(raw_input(“Entertotalnumberofcolumnsinthefirstmatrix”))
a=[[random.random()forrowinrange(m1)]forcolinrange(n1)]
foriinrange(m1):
forjinrange(n1):
a[i][j]=int(raw_input(“?“))
m2=input(“Entertotalnumberofrowsinthesecondmatrix”)
n2=input(“Entertotalnumberofcolumnsinthesecondmatrix”)
b=[[random.random()forrowinrange(m2)]forcolinrange(n2)]
foriinrange(m2):
forjinrange(n2):
b[i][j]=int(raw_input(“?“))
c=[[random.random()forrowinrange(m1)]forcolinrange(n2)]
if(n1==m2):
foriinrange(m1):
forjinrange(n2):
c[i][j]=0
foriinrange(m1):
forjinrange(n2):
forkinrange(n1):
c[i][j]+=a[i][k]*b[k][j]
printc[i][j],‘\t’,
else:
print“Multiplicationnotpossible”
4.Writeaprogramtoinputanymatrixandprintbothdiagonalvaluesofthematrix.
m=int(raw_input(“Entertotalnumberofrows”))
n=int(raw_input(“Entertotalnumberofcolumns”))
l=range(m*n)
k=0
print“Inputallmatrixelementsoneafterother”
foriinrange(m):
forjinrange(n):
l[k]=int(raw_input((“Enternewelement”)))
k=k+1
print“leftdiagonal”
k=0
foriinrange(m):
forjinrange(n):
ifi==j:
printl[k],‘\t’,
else:
print‘\t’,
k=k+1
print“rightdiagonal”
k=0
foriinrange(m):
forjinrange(n):
if(i+j)==(m-1):
printl[k],‘\t’,
else:
print‘\t’,
k=k+1
5. Writeaprogramtopassanylistandtoarrangeallnumbersindescendingorder.
defarrange(l,n):
foriinrange(n-1):
forjinrange(n-i-1):
ifl[j]<l[j+1]:
temp=l[j]
l[j]=l[j+1]
l[j+1]=temp
defmain():
l=[7,5,8,2,9,10,3]
arrange(l,len(l))
printl
if__name__==“__main__”:
main()
Practiceproblems1. Writeaprogramtocalculateanddisplaythesumofalltheoddnumbersinthelist.2. Writeaprogramforfindingamatrixrowsum,columnsumanddiagonalsum.3. Defineafunctionoverlapping()thattakestwolistsandreturnsTrueiftheyhaveat
leastonememberincommon,Falseotherwise.4. Writetheoutputfromthefollowingcode:
A=[20,40,60,80,100]
L=len(A)
S=0
forIinrange(1,L,2):
S+=A[I]
print“Sum=”,S
5.Findtheerrorsfromthefollowingprogram
n=int(raw_input(“Entertotalnumberofelements”))
l=range(n)
printl
foriin(n):
l[i]=raw_input(“enterelement”)
print“Allelementsinthelistontheoutputscreen”
forionrange(n):
printl[i]
6.Writeafunctiontofindallduplicatesinthelist.
Chapter7:DICTIONARIES
Adictionaryislikealist.Inalist,indexvalueisaninteger,whileinadictionaryindexvaluecanbeanyotherdatatypeandarecalledkeys.
AdictionaryismutableandisanothercontainertypethatcanstoreanynumberofPythonobjects,includingothercontainertypes.Adictionaryisanextremelyusefuldatastorageconstructforstoringandretrievingallkeyvaluepairs,whereeachelementisaccessed(orindexed)byauniquekey.
Dictionariesconsistofpairs(calleditems)ofkeysandtheircorrespondingvalues.Pythondictionariesarealsoknownasassociativearraysorhashtables.Wecanrefertoadictionaryasamappingbetweenasetofindices(whicharecalledkeys)andasetofvalues.Eachkeymapsavalue.Theassociationofakeyandavalueiscalledakey-valuepair.
Creatingadictionary
Eachkeyisseparatedfromitsvaluebyacolon(:),theitemsareseparatedbycommas,andthewholethingisenclosedincurlybraces.Anemptydictionarywithoutanyitemsiswrittenwithjusttwocurlybraces,likethis:{}.
Keys are unique within a dictionary while values may not be. The values of adictionary canbeof any type, but thekeysmust beof an immutabledata type such asstrings,numbers,ortuples.
Thegeneralsyntaxofadictionaryisasfollows:
dict-name={key1:value1,key2:value2….}
Example7.1:Let’screateadictionarythatmapsfromnumberstonumbernames,sothekeysvaluesareinnumbersandvaluesareinstrings.
A={1:“One”,2:“Two”,3:“Three”}
printA
Wecanalsocreateadictionarywithkeywordargumentsandthetypeconstructor,aslongasthekeysareallstrings.
bob=dict(name=‘BobSmith’,age=42,pay=30000,job=‘developer’)
sam=dict(name=‘SamuelRichard’,age=45,pay=40000,job=‘manager’)
printbob
printsam
Fig7.2:Creatingdictionary2
Wecanalsofillthedictionaryonefieldatatime.
pam={}
pam[‘name’]=‘PamelaJones’
pam[‘age’]=45
pam[‘pay’]=40000
pam[‘job’]=‘Clerk’
printpam
Fig7.3:Creatingdictionary3
CharacteristicsofPythonDictionaries
1.DictionariesareUnordered
Thedictionaryelements(key-valuepairs)arenotinorderedform.
A={1:“One”,2:“Two”,3:“Three”,6:“Six”,4:“Four”,5:“Five”}
printA
Fig7.4:Dictionary-unordered
Theorderofelementswhilethedictionarywasbeingcreatedisdifferentfromtheorderinwhichtheyareactuallystoredanddisplayed.Evenifotherelementsareaddedtothepythondictionary,theorderisnotpreserved.
2.DictionaryKeysareCaseSensitive
Thesamekeynamebutwithdifferentcasearetreatedasdifferentkeysinpythondictionaries.
worddict={}#Createanemptydictionary
worddict[“Raja”]=123233
worddict[“Rama”]=123456
worddict[“rama”]=123789
printworddict
Fig7.5:Dictionary–casesensitive
Intheexampleabove,separateelementsfor“Rama”and“rama”arecreated.
3.Noduplicatekeyisallowed
When duplicate keys encountered during assignment, the last assignment wins.Followingisasimpleexample:
phonebook={“Harry”:856321900,“Henry”:893456782,“Sony”:678903421}
printphonebook
print“DuplicatingkeySony”
phonebook[“Sony”]=900235000
printphonebook
Fig7.6:Dictionary–noduplicatekey
4.Keysmustbeimmutable
Wecanusestrings,numbersortuplesasdictionarykeysbutsomethinglike[‘key’]isnotallowed.Followingisasimpleexample:
phonebook={“Harry”:856321900,“Henry”:893456782,“Sony”:678903421}
phonebook={[‘Name’]:‘Harry’,‘Age’:50}
print“phonebook[‘Name’]:”,phonebook[‘Name’]
Fig7.7:Dictionary–immutablekeys
AccessingValuesinDictionary
To access dictionary elements, square brackets along with the key are used toobtainitsvalue.
A={1:“One”,2:“Two”,3:“Three”,6:“Six”,4:“Four”,5:“Five”}
printA
print“A[2]=”,A[2]
print“A[5]=”,A[5]
Fig7.8:Accessingvaluesindictionary
Ifweattempttoaccessadataitemwithakey,whichisnotpartofthedictionary,wegetanerrorasfollows:
A={1:“One”,2:“Two”,3:“Three”,6:“Six”,4:“Four”,5:“Five”}
printA
print“A[10]=”,A[10]
Fig7.9:AccessError–wrongkey
UpdatingDictionary
Anexistingentrycanbemodifiedbyreassigninganewvaluetothekey.
phonebook={“Harry”:856321900,“Henry”:893456782,“Sony”:678903421}
printphonebook
name=raw_input(“Enternametomodify:“)
ifnameinphonebook:
newno=raw_input(“Enternewtelephonenumber”)
phonebook[name]=newno
print“Modifiedsuccessfully”
else:
print(name,“wasnotfound”)
Fig7.10:Updatingdictionary
DeleteDictionaryElements
We can remove individual dictionary elements or clear the entire contents of adictionary.
phonebook={“Harry”:856321900,“Henry”:893456782,“Sony”:678903421}
printphonebook
name=raw_input(“Enternametodelete:“)
ifnameinphonebook:
delphonebook[name]
printname,“deletedsuccessfully”
else:
print(name,“wasnotfound”)
printphonebook
Fig7.11:Deletingdictionaryelements
Wecanalsodeleteentiredictionaryinasingleoperationusingthedelstatement.
phonebook={“Harry”:856321900,“Henry”:893456782,“Sony”:678903421}
printphonebook
delphonebook
print“Phonebookdeletedsuccessfully”
printphonebook
Fig7.12:Deletingdictionary
Built-inDictionaryFunctions&Methods
Python includes the following dictionary functions. For all these examples let’sassume
phonebook1={“Harry”:856321900,“Henry”:893456782,“Sony”:678903421}
S.No Function Description Example
1 cmp(dict1,dict2)
Thisisusedtocheckwhetherthegivendictionariesaresameornot.Ifbotharesame,itwillreturn‘zero’,otherwisereturn1or-1.Ifthefirstdictionaryhavingmorenumberofitems,thenitwillreturn1,otherwisereturn-1.
phonebook2={“Harry”:878345123,“Raja”:987652341,“Sriya”:908765432}
printcmp(phonebook1,phonebook2)
>>-1
2 len(dict)
Givesthetotallengthofthedictionary.Thiswouldbeequaltothenumberofitemsinthedictionary.
printlen(phonebook1)
>>3
3 str(dict)
Producesaprintablestring
printstr(phonebook1)
>>{‘Sony’:678903421,‘Henry’:
representationofadictionary
893456782,‘Harry’:856321900}
4 type(variable)
Returnsthetypeofthepassedvariable.Ifpassedvariableisdictionary,thenitwouldreturnadictionarytype.
printtype(phonebook1)
>><type‘dict’>
Table7.1:PythonDictionaryFunctions
Pythonincludesfollowingdictionarymethods
S.No Methods Description Example
1 dict.clear()
Itremovesallitemsfromtheparticulardictionarydict.
phonebook1.clear()
printphonebook1
>>{}
2 dict.copy()
Returnsashallowcopyofdictionarydict
phonebook2=phonebook1.copy()
printphonebook2
>>{‘Sony’:678903421,‘Harry’:856321900,‘Henry’:893456782}
3 dict.fromkeys()
Createanewdictionarywithkeysfromseqandvaluessettovalue.
printphonebook1.fromkeys(“Harry”)
>>{‘a’:None,‘H’:None,‘r’:None,‘y’:None}
4 dict.get(k,default=None)
Thefirstargumentiskey
printphonebook1.get(‘Harry’,“HarryPotter”)
value,whilethesecondargumentiscorrespondingvalue.Ifadictionaryhasagivenkey(k),whichisequaltogivenvalue(x),itreturnsthecorrespondingvalue(x)ofgivenkey(k).However,ifthedictionaryhasnokey-valuepairforgivenkey(k),thismethodreturnsthedefaultvaluessameasgivenkeyvalue.Thesecondargumentisoptional.Ifomittedandthedictionaryhasnokeyequaltothegivenkeyvalue,thenitreturnsNone.
>>856321900
printphonebook1.get(“Harry”,“Henry”)
>>856321900
printphonebook1.get(“Harry”)
>>856321900
printphonebook1.get(“Rita”)
>>None
5 dict.has_key(key)
Thisfunctionreturns‘True’,ifdictionaryhasakey,otherwiseitreturns‘False’.
printphonebook1.has_key(“Harry”)
>>True
6 dict.items() Itreturnsthe printphonebook1.items()
contentofdictionaryasalistofkeyandvalue.Thekeyandvaluepairwillbeintheformofatuple,whichisnotinanyparticularorder.
>>[(‘Sony’,678903421),(‘Henry’,893456782),(‘Harry’,856321900)]
7 dict.keys()
Itreturnsalistofthekeyvaluesinadictionary,whichisnotinanyparticularorder.
printphonebook1.keys()
>>[‘Sony’,‘Henry’,‘Harry’]
8 dict.setdefault(key,default=None)
Similartoget(),butwillsetdict[key]=defaultifkeyisnotalreadyindict
phonebook1={‘name’:‘John’,‘phone’:12390007}
printphonebook1.setdefault(‘phone’,None)
>>12390007
9 dict.update(dict2)
Addsdictionarydict2’skey-valuespairstodict
printphonebook1.update(phonebooknew)
printphonebook1
>>{‘Sony’:678903421,‘Henry’:893456782,‘Huges’:954005678,‘Harry’:856321900}
10 dict.values()
Itreturnsalistofvaluesfromkey-valuepairsina
printphonebook1.values()
>>[678903421,893456782,954005678,856321900]
dictionary,whichisnotinanyparticularorder.However,ifwecallboththeitems()andvalues()methodwithoutchangingthedictionary’scontentsbetweenthesetwo(items()andvalues()),Pythonguaranteesthattheorderofthetworesultswillbethesame.
Table7.2:PythonDictionaryMethods
SolvedPrograms1. Writeapythonprogramtoinput‘n’namesandphonenumberstostoreitina
dictionaryandtoinputanynameandtoprintthephonenumberofthatparticularname.
Ans:
phonebook={}
n=int(raw_input(“Enterthenumberofentries”))
foriinrange(n):
name=raw_input(“Name:“)
phone=raw_input(“Number:“)
phonebook[name]=phone
printphonebook
name=raw_input(“Enternametosearch:“)
ifnameinphonebook:
print(“Thenumberis”,phonebook[name])
else:
print(name,“wasnotfound”)
2.Writeaprogramtoinput‘n’employeenumberandnameandtodisplayall
employee’sinformationinascendingorderbasedupontheirnumber.
Ans:
empinfo=dict()
n=int(raw_input(“Entertotalnumberofemployees”))
i=1
whilei<=n:
a=raw_input(“enternumber”)
b=raw_input(“entername”)
empinfo[a]=b
i=i+1
l=empinfo.keys()
l.sort()
print“EmployeeInformation”
print“EmployeeNumber”,‘\t’,“EmployeeName”
foriinl:
printi,‘\t’,empinfo[i]
3.Writeaprogramtoformafrequencytableofwordsinagiventext.
Ans:
freq={}#frequencyofwordsintext
line=raw_input(“Entertext:“)
line=line.lower()
forchin‘!%.?,{”}’:
line=line.replace(ch,‘‘)
forwordinline.split():
freq[word]=freq.get(word,0)+1
words=freq.keys()
words.sort()
forwinwords:
print“%s:%d”%(w,freq[w])
PracticeProblems
1.Writethecodetoinputany5yearsandthepopulationofanycityandprintitonthescreen.
2.Writeaprogramtosimulateaphonebook.
3.Writeacodetocreatecustomer’slistwiththeirnumber&nameanddeleteanyparticularcustomerusinghis/hernumber.
4.Writetheoutputforthefollowingcodes.
A={10:1000,20:2000,30:3000,40:4000,50:5000}
printA.items()
printA.keys()
printA.values()
5.WriteaPythonprogramtoinput‘n’namesandphonenumberstostoreitinadictionaryandprintthephonenumberofaparticularname.
6.Writeaprogramtocreateaphonebookanddeleteparticularphonenumberusingname.
7.Finderrorsfromthefollowingcodes:
c=dict()
n=input(Entertotalnumber)
i=1
whilei<=n
a=raw_input(“enterplace”)
b=raw_input(“enternumber”)
c[a]=b
i=i+1
print“place”,“\t”,“number”
foriinc:
printi,“\t”,c[a[i]]
Chapter8:Tuples
Atupleisasequenceofvalues,whichcanbeofanytypeandtheyareindexedby
integer.Tuplesarejustlikelist,butwecan’tchangevaluesoftuplesinplace.Thustuplesareimmutable.Theindexvalueoftuplestartsfrom0.
TupleCreation
Atupleconsistsofanumberofvaluesseparatedbycommas.
Ex8.1:Tuplecreation
tup1=(‘desktop’,‘laptop’,1997,2000)
tup2=(1,2,3,4,5)
tup3=“a”,“b”,“c”,“d”
printtup1
printtup2
printtup3
Butintheresult,sametupleisprintedusingparentheses.Tocreateatuplewithsingleelement,wehavetousefinalcomma.Avaluewithintheparenthesisisnottuple.
Theemptytupleiswrittenastwoparenthesescontainingnothing:
tup1=()
Towriteatuplecontainingasinglevaluewehavetoincludeacomma,eventhoughthereisonlyonevalue:
tup1=(50,);
Example8.2:Createtupleswithsinglecharacter.
T=(‘P’,‘Y’,‘T’,‘H’,‘O’,‘N’)
printT
Anotherwayofcreatingtupleisbuilt-infunctiontuple().
T=tuple()
printT
Fig8.1:creatingtupleusingbuilt-infunction
Tupleinsertion
Wecanaddnewelementtotupleusing+operator.
t=(1,2,3,4)
t+(5,)#thiswillnotcreatemodificationoft.
printt
t=t+(5,)#thiswilldomodificationoft.
printt
Fig8.2:Tupleinsertion
Example8.3:Writeaprogramtoinput‘n’numbersandstoreitintuple.
t=tuple()
n=input(“Entercountofnumbers”)
print”enterallnumbersoneafterother”
foriinrange(n):
a=input(“enternumber”)
t=t+(a,)
print“outputis”
foriinrange(n):
printt[i]
Wecanalsoaddnewelementtotuplebyusinglist.Forthatwehavetoconvertthetupleintoalistfirstandthenuseappend()functiontoaddnewelementstothelist.Aftercompletingtheaddition,convertthelistintotuple.
Example8.4:Addnewelementstotupleusingalist.
T=tuple()#createemptytuple
l=list(T)#converttupleintolist
l.append(11)#Addnewelementstolist
l.append(22)
T=tuple(l)#convertlistintotuple
printT
Tupleinitialization
Wecaninitializeatupleasfollows
T=(0,)*5
printT
Fig8.3:Tupleinitialization
TupleAssignment
Ifwewanttointerchange(swap)anytwovariablevalues,wehavetousetemporaryvariable.Butinpython,tupleassignmentismoreelegant.
T1=(10,20,30)
T2=(100,200,300,400)
T1,T2=T2,T1#swapT1andT2
printT1
printT2
Fig8.4:Tupleassignment
Theleftsideisatupleofvariables,whiletherightsideisatupleofexpressions.Eachvalueisassignedtoitsrespectivevariable.Alltheexpressionsontherightsideareevaluatedbeforeanyoftheassignments.Thenumberofvariablesontheleftandthenumberofvaluesontherighthavetobethesame.
T1=(10,20,30)
T2=(100,200,300)
T3=(1000,2000,3000)
T1,T2=T2,T1,T3
Fig8.5:Tupleassignmenterror
Here,twotuplesareintheleftsideandthreetuplesareinrightside.Thatiswhy,wegeterrors.Thus,itisrequiredtohavesamenumberoftuplesinbothsidestogetthecorrectresult.
TupleSlices
SliceoperatorworksonTuplealso.Thisisusedtodisplaymorethanoneselectedvalueontheoutputscreen.Slicesaretreatedasboundariesandtheresultwillcontainalltheelementsbetweenboundaries.
Syntax:Seq=T[start:stop:step]
Wherestart,stop&stepallthreeareoptional.Ifweomitfirstindex,slicestartsfrom‘0’.Onomittingstop,slicewilltakeittoend.Defaultvalueofstepis1.
T=(1,2,3,4,5)
printT
T1=T[2:4]
print“T[2:4]=”,T1
print“T[:]=”,T[:]#Willproduceacopyofthewholetuple.
print“T[::2]=”,T[::2]#WillproduceaTuplewitheveryalternateelement.
print“T[:3]=”,T[:3]#Willproduce0to2(3-1)
print“T[2:]=”,T[2:]#Willproducefrom2toend.
Fig8.6:Tupleslice
UpdatingTuples
Tuplesareimmutablewhichmeansyoucannotupdatethemorchangevaluesoftupleelements.
tup1[0]=100;#Invalid
Butweabletotakeportionsofanexistingtuplestocreateanewtuplesasfollows.
tup1=(12,34.56);
tup2=(‘abc’,‘xyz’);
tup3=tup1+tup2;
printtup3;
Fig8.7:Tupleupdation
DeleteTupleElements
Itisnotpossibletoremoveindividualtupleelements.Thereis,ofcourse,nothingwrong with putting together another tuple with the undesired elements discarded. Toexplicitlyremoveanentiretuple,justusethedelstatement.
T=(1,2,3,4,5)
printT
delT
printT
Fig8.8:Tupledeletion
BasicTuplesOperations
Tuples respond to the + and * operators much like strings; they meanconcatenationandrepetitionheretoo,exceptthattheresultisanewtuple,notastring.
Description PythonExpression
Results
Length len((1,2,3)) 3
Concatenation (1,2,3)+(4,5,6)
(1,2,3,4,5,6)
Repetition [‘Hello!’]*4 (”Hello!’,”Hello!’,”Hello!’,”Hello!’)
Membership 1in(1,2,3) True
Iteration forxin(1,2,3):
printx,
123
Table8.1:Tupleoperations
Built-inTupleFunctions
Pythonincludesthefollowingtuplefunctions
S.No Function Description Example
1 cmp(tuple1,tuple2)
Thisisusedtocheckwhetherthegiventuplesaresameornot.Ifbotharesame,itwillreturn‘zero’,otherwisereturn1or-1.Ifthefirsttupleisbig,thenitwillreturn1,otherwisereturn-1.
tuple1=(11,22,33,44,55)
tuple2=(111,222,333,444,555)
printcmp(tuple1,tuple2)
>>-1
2 len(tuple)
Itreturnsthenumberofitemsinatuple.
printlen(tuple1)
>>5
3 max(tuple)
Itreturnsitslargestiteminthetuple.
printmax(tuple1)
>>55
4 min(tuple)
Itreturnsitssmallestiteminthetuple.
printmin(tuple1)
>>11
5 tuple(seq)
Convertsalistintotuple.
seq=[1,2,3,4,5]
printtuple(seq)
>>(1,2,3,4,5)
Table8.2:Tuplebuilt-infunctions
SolvedPrograms1. Writeaprogramtoinput5subjectnamesandputitintupleanddisplaythat
tupleinformationontheoutputscreen.
Ans:
t=tuple()
print”Enter5courses”;
foriinrange(5):
a=raw_input(“Entercoursename”)
t=t+(a,)
print“outputis”
printt
2. Writeaprogramtoinputanytwotuplesandinterchangethetuplevalues.
Ans:
t1=tuple()
n=input(“Totalnumberofvaluesinfirsttuple”)
foriinrange(n):
a=input(“enterelements”)
t1=t1+(a,)
t2=tuple()
m=input(“Totalnumberofvaluesinfirsttuple”)
foriinrange(m):
a=input(“enterelements”)
t2=t2+(a,)
print“FirstTuple”
printt1
print“SecondTuple”
printt2
t1,t2=t2,t1
print“AFTERSWAPPING”
print“FirstTuple”
printt1
print“SecondTuple”
printt2
PracticeProblems1. Writeaprogramtoinput‘n’employees’salaryandfindminimum&maximumsalary
among‘n’employees.
2.Writetheoutputfromthefollowingcodes;
(i)t=(10,20,30,40,50)
printlen(t)
(ii)t=(‘a’,‘b’,‘c’,‘A’,‘B’)
max(t)
min(t)
(iii)T1=(10,20,30,40,50)
T2=(10,20,30,40,50)
T3=(100,200,300)
cmp(T1,T2)
cmp(T2,T3)
cmp(T3,T1)
(iv)t=tuple()
Len(t)
(iv)T1=(10,20,30,40,50)
T2=(100,200,300)
T3=T1+T2
printT3
3.Writeaprogramtoinputtwosetvaluesandstoreitintuplesandalsodothecomparison.
4.Findtheerrorsfromthefollowingcode:
t=tuple{}
n=input(Totalnumberofvaluesintuple)
foriinrange(n)
a=input(“enterelements”)
t=t+(a)
print“maximumvalue=”,max(t)
print“minimumvalue=”,min(t)
5.Writeaprogramtoinput‘n’numbersandseparatethetupleinthefollowingmanner.
Example
T=(10,20,30,40,50,60)
T1=(10,30,50)
T2=(20,40,60)
6.Findtheoutputfromthefollowingcode:
T=(10,30,2,50,5,6,100,65)
printmax(T)
printmin(T)
7.Findtheoutputfromthefollowingcode:
t=tuple()
t=t+(PYTHON,)
printt
printlen(t)
t1=(10,20,30)
printlen(t1)
Chapter9:Classes,ObjectsandInheritance
Aclassisadefinitionofanobject.Aclassisauserdefineddatatypejustlikeint,andanobjectofthisclassisjustavariable.Whenwedefineaclass,wedefineablueprintfor a data type. A class is used to specify the form of an object and it combines datarepresentationandmethodsformanipulatingthatdataintooneneatpackage.Thedataandfunctionswithinaclassarecalledmembersoftheclass.
Namespaces
Anamespaceisamappingfromnamestoobjects.Itisaplacewhereavariable’snameisstored.Pythonhasthefollowingnamespacesandsearchesinthefollowingorder.
Localcanbeinsideafunctionorclassmethod,forexampleinsidedef
Enclosedcanbeitsenclosingfunction,e.g.,ifafunctioniswrappedinsideanotherfunction.Thevariableissearchedinallenclosingfunctionsfrominnertoouter.
Globalreferstotheuppermostlevel.Thevariableissearchedinglobalmodulesorfornamesdeclaredglobalinadef.
Built-inarespecialnamesthatPythonreservesforitself.
Fig9.1:PythonNamespaces
Definingclasses
A class definition starts with the keyword class followed by the class name and acolon;ForexamplewedefinedtheStudentdatatypeusingthekeywordclassasfollows:
classStudent:
count=0
#constructortocreateanobject
def__init__(self,rollno,marks):
self.rollno=rollno
self.marks=marks
defread(self):#Thisfunctiongetsthedetailsofastudentfromtheuser
Student.count+=1
defdisplay(self):#Thisfunctionprintseachstudent’sdetails
In the above class definition rollno,marks,read() and display() are attributes of theclassstudent.
The init function is the first method and is a special method called constructor orinitializationmethod.Itisusedtoinitializethedatamembersofaclass.Itisthefirstpieceofcodeexecutedinanewlycreatedinstanceoftheclass.
Itcantakeanynumberofargumentsandalsodefaultarguments.
Objects
Anobject iscreated fromaclass.Wedeclareobjectsofaclasswithexactly thesame sort of declaration thatwe declare variables of basic types. Following statementsdeclaretwoobjectsofclassStudent:
S1=Student();//Declares1oftypeStudent
S2=Student();//Declares2oftypeStudent
Bothoftheobjectss1ands2willhavetheirowncopyofdatamembers.
Objectsofaclasshaveasamestructureandbehavior.Theywillonlydifferregardingtheirstate(values).
Self
Thefirstargumentofeveryclassmethodisalwaysareferencetothecurrentinstanceof the class named “self”. This is the only difference between a class method and anordinaryfunction.“self”isnotakeywordandisjustusedforreadabilityanduniformity.Itisaninstanceidentificator.
Hereisanexampleusingself
classStock:
discount=5
#constructortocreateanobject
def__init__(self,icode,price,qty):
self.icode=icode
self.price=price
self.qty=qty
#Displaysitemdetails
defdisplay(self):
print“ItemCode:”,self.icode
print“Price:Rs”,self.price
print“Quantity:“,self.qty
Intheaboveexample,discountisaclassvariablewhosevaluewouldbesharedamongallinstancesofthisclass.Theycanbeaccessedas
Stock.discount
Instance attributes belong to each instance/object of a class. i.e. S1.icode ands2.icodewillhave2differentvalues
ACCESSINGATTRIBUTES
Attributescanbeaccessedbyusingthedotoperator.
Thegetattr(obj,name[,default]):toaccesstheattributeofobject.
Thehasattr(obj,name):tocheckifanattributeexistsornot.
Thesetattr(obj,name,value):tosetanattribute.Ifattributedoesnotexist,thenitwouldbecreated.
Thedelattr(obj,name):todeleteanattribute.
getattr(obj1,‘price’)#Returnsvalueof‘price’attribute
hasattr(obj1,‘price’)#Returnstrueif‘price’attributeexists
setattr(obj1,‘price’,30.56)#Setattribute‘price’at30.56
delattr(obj1,‘price’)#Deleteattribute‘price’
BUILT-INCLASSATTRIBUTES
EveryPythonclasskeepsfollowingbuilt-inattributesandtheycanbeaccessedusingdotoperatorlikeanyotherattribute:
__dict__:Dictionarycontainingtheclass’snamespace.
__doc__:ClassdocumentationstringorNoneifundefined.
__name__:Classname.
__module__:Modulenameinwhichtheclassisdefined.Thisattributeis“__main__”ininteractivemode.
__bases__:Apossiblyemptytuplecontainingthebaseclasses,intheorderoftheiroccurrenceinthebaseclasslist.
__del()__ordestructor
Thisfunctioniscalledwhentheinstanceisabouttobedestroyed.Itcallsthemethod-object.__del__(self)
Considerthefollowingcommandisgiven
>>>delS1
Theabovecommanddoesn’tdirectlycallS1.__del__().FirstthereferencecountforS1isdecrementedbyoneand__del()__iscalledonlywhenS1’sreferencecountreacheszeroi.e.whenallthevariablesreferencedbyS1havebeendeleted.
__str()__
Itisaspecialfunctionwhichreturnsthestringrepresentationoftheobjects.Itcallsthemethod
object.__str__(self).Iftheclassdefinesa__str__method,Pythonwillcallitwhenyoucallthestr()oruseprintstatement.Thestr()built-infunction,whenusedalongwiththeprintstatementcomputesthe“informal”stringrepresentationofanobject.
classStudent:
……….
………..
def__str__(self):
return“ThisclassisaboutaStudent?”
>>>S=Student()
>>>printS
Hello,Howareyou?
Whenyougivethecommandto“printS”,Pythoncallsstr(S)togetthestringrepresentationofS.IftheclassofShasa__str__method,str(S)becomesacalltoS.__str__().Thisreturnsthestringtoprint.
Privatevariables
“Private” instance variables are not supported in Python. It can be achievedthroughnamemangling.Aname isprefixedwith two leadingunderscoresandnomorethanonetrailingunderscoretomakeitasaprivatemember.
ClassStudent:
Rollno=121
Grade=‘A’
__age=15#privatemember
Datahiding is ameans to enforce encapsulation.Toaccess thishiddenvariable,weneedtofollowthesyntax
ClassName.__var-name
Ex:-Student.__age=20
DYMANICALLYADDINGMETHODS
DynamicClassMethodAddition
Occasionallyyoumayneeddynamicallyaddafunctionasamethodtoaclass.Thisiseasilyaccomplishedbyassigningthefunctionasanattributeoftheclass.
deffn(self):
returnid(self),self,type(self)
classA_Class(object):
defmethod_a(self):
returnid(self),self,type(self)
A=A_Class()
#Modifytheclassandaddfnasamethod
setattr(A_Class,‘method_b’,fn)
A.method_a()
#Callthedynamicallyaddedmethod
A.method_b()
DynamicInstanceMethodAddition
Whenweaddthemethodtoaclassallinstancescanaccessit.Ifweonlywantaparticularinstancetohaveamethoddothis:
fromtypesimportMethodType
A=A_Class()
setattr(A,fn.__name__,MethodType(fn,A,type(A)))
#CallsthefnmethodattachedtotheinstanceA
A.fn()
#Throwsanexception
A.fn()
StaticMethods
Astaticmethodiscallablewithoutanobject.
classStudent:
@staticmethod
defgetStudentcount():
returncount
printStudent.getStudentCount()
In the above example, the function getStudentcount () dosen’t use self. They areprecededwith a decorator@staticmethod and it is being calledwithout the instance. Iteasesthereadabilityofthecode.Staticmethodsareaccessiblefromeitheranobjectoraclass.
DestroyingObjects(GarbageCollection)
Pythonautomaticallyallocatesandde-allocatesmemory.TheuserdoesnothavetopreallocateordeallocatememorybyhandasonehastowhenusingdynamicmemoryallocationinlanguagessuchasCorC++.Pythonusestwostrategiesformemoryallocation-referencecountingandautomaticgarbagecollection.
i)ReferenceCounting
Referencecountingcountsthenumberoftimesanobjectisreferencedbyotherobjectsinthesystem.Anobject’sreferencecountchangesasthenumberofaliasesthatpointtoitchange.Anobject’sreferencecountincreaseswhenitisassignedanewnameorplacedinacontainer(list,tupleordictionary).Theobject’sreferencecountdecreaseswhenitisdeletedwithdel,itsreferenceisreassigned,oritsreferencegoesoutofscope.Whenanobject’sreferencecountreacheszero,Pythoncollectsitautomatically.
Considerthecodegivenbelow:
A=5#anobjectAiscreatedwhichisboundto5.
B=A#increaseinreferencecountof5
C[0]={B}#increaseinreferencecountof5
delA#decreaseinreferencecountof5
B=10#decreaseinreferencecountof5
Aclasscanimplementthespecialmethod__del__(),calledadestructor,thatisinvokedwhentheinstanceisabouttobedestroyed.Referencecountingisextremelyefficientbutitcannothandlereferencecycles.Areferencecycleiswhenthereisnowaytoreachanobjectbutitsreferencecountisstillgreaterthanzero.Theeasiestwaytocreateareferencecycleistocreateanobjectwhichreferstoitselfasintheexamplebelow:
defreference_cycle():
x=[]
x.append(x)
reference_cycle()
Intheaboveexamplesincereference_cycle()createsanobjectxwhichreferstoitself(statementx.append(x)),xwillnotautomaticallybefreedwhenthefunctionreturns.ThiswillcausethememorythatxisusingtobeheldontountilthePythongarbagecollectorisinvoked.
ii)AutomaticGarbageCollection
Inthiscasegarbagecollectionisascheduledactivity.Pythonschedulesgarbagecollectionbaseduponathresholdofobjectallocationsandobjectde-allocations.Pythondeletestheobjectswhicharenotrequired,mayitbebuilt-intypesorclassinstances,throughtheprocessnamedgarbagecollection.
Whenthenumberofallocationsminusthenumberofde-allocationsaregreaterthanthethresholdnumber,thegarbagecollectorisrunandtheunusedblockofmemoryisreclaimed.Onecaninspectthethresholdfornewobjectsbyloadingthegcmoduleandaskingforgarbagecollectionthresholds.
AutomaticgarbagecollectionwillnotrunifyourPythondeviceisrunningoutofmemory.Insuchcase,yourapplicationwillthrowexceptions,whichmustbehandledotherwiseyourapplicationwillcrash.Itoccursmoreforthenumberoffreeobjectsnotthesizeofobjects.
Inheritance
Inheritanceallowsustodefineaclassintermsofanotherclass,whichmakesiteasiertocreateandmaintainanapplication.Thisalsoprovidesanopportunitytoreusethecodefunctionalityandfastimplementationtime.
Whencreatingaclass,insteadofwritingcompletelynewdatamembersandmemberfunctions,theprogrammercandesignatethatthenewclassshouldinheritthemembersofanexistingclass.Thisexistingclassiscalledthebaseclass,andthenewclassisreferredto as the derived class. The idea of inheritance implements the IS-A relationship. Forexample,mammalIS-Aanimal,dogIS-AmammalhencedogIS-Aanimalaswellandsoon.
Formsofinheritance
Singleinheritance:Whenasubclassinheritsfromonlyonebaseclass,andthereareonly2classesinthisrelationship,thenitisknownassingleinheritance.
Fig10.1:SingleInheritance
Multilevelinheritance:Whenasubclassinheritsfromaclassthatitselfinheritsfromanotherclass,itisknownasmultilevelinheritance.
Fig10.2:MultilevelInheritance
Multipleinheritance:Whenasubclassinheritsfrommultiplebaseclassesitisknownasmultipleinheritance.
Fig10.3:MultipleInheritance
Hierarchicalinheritance:Whenmanysubclassesinheritfromasinglebaseclassitisknownashierarchicalinheritance.
Fig10.4:HierarchicalInheritance
Hybridinheritance:Hybridinheritancecombines2ormoreformsofinheritance.
Fig10.5:HybridInheritance
BaseOverloadingMethods
S.No Method Description Usage
1 __init__(self[,args…])
Constructor obj=className(args)
2 __del__(self)
Destructor,deletesanobject
delobj
3 __repr__(self)
Evaluateablestringrepresentation
repr(obj)
4 __str__(self) Printablestringrepresentation
str(obj)
5 __cmp__(self,x)
Comparisonofobjects
cmp(obj,x)
SingleInheritance
Person is the base class from which a student derives. It has 2 private datamembers:person’snameasstringandageasaninteger.Ithas2methodsread()anddisp()togetanddisplaypersondetails.
Studentclass isdefinedwithrollnumberasan integerandaverageasfloat. Ithas3memberfunctions
readStudent()–internallycallsread()ofPersonclassandgetstherollnoandaverageofstudent.
disprollno()–displaysrollnumberofstudent
getaverage()–returnstheaverageofthestudent
Fig10.6:SingleInheritanceexample
classPerson(object):
#constructortocreateanobject
def__init__(self):
self.name=””
self.age=0
defget(self):
self.name=raw_input(“EntertheName:”)
self.age=int(raw_input(“Age?”))
defdisp(self):
print“Name:”,self.name,“\tAge:”,self.age
classStudent(Person):
#constructortocreateanobject
def__init__(self):
super(Student,self).__init__()
self.rollno=0
self.avg=0.0
defreadStudent(self):
#Callgetmethodofparentclass
super(Student,self).get()
self.rollno=int(raw_input(“EntertheRollNumber:”))
self.avg=float(raw_input(“Average?”))
defdisprollno(self):
print“RollNo.:”,self.rollno
defgetaverage(self):
returnself.avg
TheclassStudentextendstheclassPerson.Theclassstudentadds2newinstancevariablesrollnoandavg.Inordertoaddnewinstancevariables,the__init__()methoddefinedinclassPersonneedstobeextended.ThisfunctionofsubclassStudentinitializesthenameandageattributesofthesuperclassPersonandalsocreatesnewattributesrollnoandavg.
Let’sexecutethefollowingstatements
p=Person()
p.get()
s=Student()
s.readStudent()
Itwouldproducethefollowingoutput.
Intheabovecodesegment,theobject(p)ofclasspersontakesvaluesforinstancevariablesnameandage.Theobject(s)ofclassstudentcaninvokereadstudent()function.
Theinitfunctioncanbeextendedinin2ways.
(i)Byusingsuper()function:Theinit()methodisdefinedinthebaseclassandisextendedinthesubclass.Super()functionisusedtocallbaseclassmethodswhichhasbeenextendedinderivedclass.
Ex:-super(Student,self).__init__(self,name,age)
(ii)Byusingsuperclass’sname:Thenameofthebaseclasscanalsobeusedtoaccessthemethodofthebaseclasswhichhasbeenextended.
Ex:-Person.__init__(self,name,age)
MULTILEVELINHERITANCE
Theabovesingleinheritancecanbeextendedtoamultilevelinheritance.GradStudentisanotherclasswhichderivesfromtheclassStudent.SoGradStudentindirectlyinheritsfromPersonclass.Ithas2memberssubjectofgraduationandworkstatusasasingle
charactery-yesandn-no.Ithas3memberfunctions
readGrad()–callsreadStudent()togetstudentdetails(whichinturncallsread()ofPersonclass)andalsogetstheGraduate’sdetails
workstatus()–returnstheworkstatusyorn
displaySubject()–printsthesubject
classGradStudent(Student):
def__init__(self):
super(GradStudent,self).__init__()
self.subject=””
self.working=”
defreadGrad(self):
#CallreadStudentmethodofparentclass
super(GradStudent,self).readStudent()
self.subject=raw_input(“Entersubjectofgraduation”)
self.working=raw_input(“Working?y/n”)
defworkstatus(self):
returnself.working
defdisplaysubject(self):
print“Subject:”,self.subject
Thesamewayinit()andtheothermethodscanbecalledusingsuperortheclassname.
MultipleInheritance
Python supportsmultiple inheritance. The general syntax ofmultiple inheritance is
givenbelow.
classDerived(Base1,Base2,Base3):
<statement1>
……
<statementN>
Ifanattribute/methodisnotfoundinDerived,itissearchedinBase1andonlyifitisnotthereitissearchedinthesubsequentbaseclasses.
MethodOverriding
Overridingenablestheprogrammertoprovidespecificimplementationtoamethodinthederivedclass.So,themethodinvokeddependsontheobjectusedtoinvokeit.Ifbaseclassobjectisusedthenbaseclassversionofthemethodiscalledelsethederivedclassmethodiscalled.
Theissubclass(sub,sup)booleanfunctionreturnstrueifthegivensubclasssubisindeedasubclassofthesuperclasssup.
Theisinstance(obj,Class)booleanfunctionreturnstrueifobjisaninstanceofclassClassorisaninstanceofasubclassofClass
Abstractmethods
Anunimplementedmethodiscalledanabstractmethod.Thesemethodsaredeclaredinaparentclass,butnotimplementedinit.Theimplementationisdoneinthederivedclass.
classShape(object):
deffindArea(self):
raiseNotImplementedError
S=Shape()
S.findArea()
Wegetthefollowingerror
Now,theaboveclasscanbeextendedasbelow
classShape(object):
deffindArea(self):
raiseNotImplementedError
classSquare(Shape):
def__init__(self,side):
self.side=side
deffindArea(self):
returnself.side*self.side
S=Square(10)
printS.findArea()
Theoutputoftheprogramisshownbelow
Whenanabstractmethodisdeclaredinabaseclass,thederivedclasshastoeither
definethemethodorraise“NotImplementedError”.
Theerrorwillberaisedonlyifwetrytousethatmethod.Thismightbeusefulwhenwedonotwanttoimplementcertainmethodsinthederivedclass.Butifweneedtoensurethatthederivedclassoverridesthismethodwecouldusethe“abc”moduleofPython.
importabc
classShape(object):
__metaclass__=abc.ABCMeta
@abc.abstractmethod
deffindArea(self):
“““Methodthatshoulddosomething.”””
classSquare(Shape):
def__init__(self,side):
self.side=side
deffindArea(self):
returnself.side*self.side
S1=Shape()
S2=Square(10)
HeretheobjectS2doesn’tcreateaproblembecausethefindArea()methodisimplemented.
SolvedQuestions
1.Whatdoyouunderstandaboutamember function?Howdoes itdiffer fromanordinaryfunction?
Ans:Amemberfunctionispartofaclassandcanbecalledonlywithanobject.Anordinaryfunctioncan’tbecalledbyanobject.Amemberfunctiontakes“self”asthefirstargumentwhileanordinaryfunctiondoesn’t.
2.Predicttheoutputofthefollowingcodesnippet
ptr=40
defresult():
printptr
ptr=90
deffunc(var):
ifvar<=60:
ptr=30
printptr
result()
func(60)
func(70)
Ans:
UnboundLocalError:localvariable‘ptr’referencedbeforeassignment
3.Predicttheoutputofthefollowingcodesnippet
ptr=50
defresult():
globalptr
ptr=ptr+1
Percentage ofmarks
Grade
80to100 A
printptr
result()
printptr
Ans.
51
51
4.Namethemethodsthatcanbeusedto
a.accessattributeofanobject
b.deleteanattributeofanobject
Ans.
a.getattr(obj,name[,default])
b.delattr(obj,name)
5.Givethestatementto
a.CheckwhethertheattributestrexistsintheclassTestwhoseobjectisT1
b.Assignavalue“Hello”totheattributestrofclassTestandobjectT1.
Ans.
a.hasattr(T1,str)
b.setattr(T1,str,“Hello”)
6.WriteaPythonprogramusingclassesandobjectstosimulateresultpreparationsystemfor20students.Thedataavailableforeachstudentincludes:Name,Rollno,andMarksin3subjects.Thepercentagemarksandgradearetobecalculatedfromthefollowinginformation
Gradeformula
Alsodemonstrateconstructoroverloading.
Ans.
60to80 B
45to60 C
Lessthan45 D
classStudent:
#constructortocreateanobject
def__init__(self,s=None):
#non-copyconstructor
ifs==None:
self.rollno=0
self.name=”
self.marks=[0,0,0]
self.avg=0.0
self.grade=”
#copyconstructor
else:
self.rollno=s.rollno
self.name=s.name
self.marks=s.marks
self.avg=s.avg
self.grade=s.grade
defread(self):
#Thisfunctiongetsthedetailsofastudentfromtheuser
self.rollno=raw_input(“Enterrollnumber:-”)
self.name=raw_input(“Entername:-”)
s=0
foriinrange(0,3):
self.marks[i]=int(raw_input(“Enterthemarks?”))
s=s+self.marks[i]
self.avg=s/3
if(self.avg>60):
self.grade=‘A’
elifself.avg>40:
self.grade=‘B’
else:
self.grade=‘C’
defdisplay(self):
#Thisfunctionprintseachstudent’sdetails
printself.rollno,“\t”,self.name,“\t\t”,self.grade
s=Student()
studlist=[]
num=int(raw_input(“Enterno.ofstudents:-”))
foriinrange(0,num):
s.read()
studlist.append(Student(s))
print”STUDENTREPORT\n”
print“*******************************************\n”
print“RollNo\tName\t\tGrade”
print“*******************************************\n”
foriinrange(0,num):
studlist[i].display()
#Initializeavgasthefirststudent’savg
maxavg=studlist[0].avg
totavg=0
foriinrange(1,num):
totavg=totavg+studlist[i].avg
ifstudlist[i].avg>maxavg:
maxavg=studlist[i].avg
topper=studlist[i].name
totavg=totavg/num
print“Classtopperis”,studlist[i].name,“withaverage”,studlist[i].avg
print“Classaverageis”,totavg
7.DefineaclassTravelinPythonwiththefollowingdescriptions:
PrivateMembers:
PlanCodeoftypelong
Placeoftypecharacterarray(string)
No_of_travellersoftypeinteger
No_of_busesoftypeinteger
PublicMembers:
AconstructortoassigninitialvaluesofPlanCodeas1001,Placeas“Agra”,
No_of_travellersas5,No_of_busesas1
AfunctionNewPlan()whichallowsusertoenterPlanCode,Placeand
No_of_travellers.Also,assignthevalueofNo_of_busesasperthe
followingconditions:
No_of_travellersNo_of_buses
Lessthan201
Equaltoormorethan20andlessthan402
Equalto40ormorethan403
AfunctionShowPlan()todisplaythecontentofallthedatamembersonscreen.
Ans:
classTravel:
def__init__(self):
self.PlanCode=1001
self.Place=“Agra”
self.No_of_travellers=5;
self.No_of_buses=1;
defNewPlan(self):
self.PlanCode=input(“Enterplancode”)
self.Place=raw_input(“EnterPlace”)
self.No_of_travellers=input(“EnterNo.oftravellers”)
if(self.No_of_travellers<20):
self.No_of_buses=1;
elif(self.No_of_travellers<40):
self.No_of_buses=2;
else:
self.No_of_buses=3;
defShowPlan(self):
printself.PlanCode,self.Place,self.No_of_travellers,self.No_of_buses
t=Travel()
t.NewPlan()
t.ShowPlan()
8.Definetheterminheritance.
Ans.Inheritanceisamechanisminwhichanewclassisderivedfromanalreadydefinedclass.Thederivedclassisknownasasubclassorachildclass.Thepre-existingclassisknownasbaseclassoraparentclassorasuperclass.Themechanismofinheritancegivesrisetohierarchyinclasses.Themajorpurposeofinheritingabaseclassintooneormorederivedclassiscodereuse.Thesubclassinheritsallthemethodsandpropertiesofthesuperclass.
9.Giveoneexampleforabstractmethod?
Ans.Anabstractmethodisamethoddeclaredinaparentclass,butnotimplementedinit.Theimplementationofsuchamethodcanbegiveninthederivedclass.
classcircle(object):
defget_radius(self):
10.Whatissingleinheritance?
Ans.:Insingleinheritanceasubclassisderivedfromasinglebaseclass.
11.Whatismultipleinheritance?Explainwithanexample.
Ans.:Inthistypeofinheritance,thederivedclassinheritsfromoneormorebaseclasses.Inthefigurebelow,XandYarethebaseclasseswhileZisthederivedclass.
12.Giveoneexampleofmultilevelinheritance.
Ans.:Inmultilevelinheritance,thederivedclassbecomesthebaseofanotherclass.
Ex:CountryisthebaseclassofStateandCityisthederivedclassofState.
13.DefineaclassemployeeinPythonwiththegivenspecifications:
Instancevariables:
Employeenumber,name
Methods:
Getdata()-Toinputemployeenumberandname
Printdata()-Todisplayemployeenumberandname
Defineanotherclasspayroll,whichisderivedfromemployee
Instancevariable
SalaryomputerScience
Methods:
Inputdata()-TocallGetdata()andinputsalary.
Outdata()-Tocallprintdata()andtodisplaysalary.
Defineanotherclassleave,whichisderivedfrompayroll.
Instancevariable
Noofdays
Methods:
acceptdata()-TocallInputdata()andinputnoofdays.
showdata()-TocallOutdata()andtodisplaynoofdays.
Implementtheaboveprograminpython.
Ans.
classEmployee(object):
#constructortocreateanobject
def__init__(self):
self.eno=0
self.name=”
defGetdata(self):
self.eno=input(“EntertheEmployeeno:”)
self.name=raw_input(“EntertheEmployeeName:”)
defPrintdata(self):
print“EmployeeNumber”,self.eno
print“EmployeeName”,self.name
classpayroll(Employee):
def__init__(self):
super(payroll,self).__init__()
self.salary=0
defInputdata(self):
self.Getdata()
self.salary=float(raw_input(“Enterthesalary:”))
defOutdata(self):
self.Printdata()
print“Salaryis”,self.salary
classleave(payroll):
def__init__(self):
super(leave,self).__init__()
self.Noofdays=0
defacceptdata(self):
self.Inputdata()
self.Noofdays=input(“Enterleavedays”)
defshowdata(self):
self.Outdata()
print“No.ofleavedays”,self.Noofdays
leaveobj=leave()
leaveobj.acceptdata()
leaveobj.showdata()
PracticeQuestions1. HowareobjectsdestroyedinPython?2. CanweaddmethodsdynamicallyinPython?Explainwithanexample.3. ExplaintheimportanceofselfinPythonclasses.4. DefineaclassITEMINFOinPythonwiththefollowingdescription:
ICode(ItemCode),Item(ItemName),Price(Priceofeachitem),Qty(quantityinstock),Discount(Discountpercentageontheitem),Netprice(FinalPrice)
Methods
AmemberfunctionFindDisc()tocalculatediscountasperthefollowingrule:
IfQty<=10Discountis0
IfQty(11to20)Discountis15
IfQty>=20Discountis20
Aconstructor(__init__method)toassignthevaluewith0forICode,Price,Qty,NetpriceandDiscountandnullforItemrespectively
AfunctionBuy()toallowusertoentervaluesforICode,Item,Price,QtyandcallfunctionFindDisc()tocalculatethediscountandNetprice(Price*Qty-Discount).
AFunctionShowAll()toallowusertoviewthecontentofallthedatamembers
5.DefineaclassBankinPythonwiththefollowingdescription:Datamembers:Nameofthedepositor:String,Accountnumber:long,Typeofaccount(Savingsorcurrent):character,Balanceamount:decimal.
MemberFunctions:
Initialize()–Itreadsthecustomername,accountnumber;accounttypeandcurrentbalanceandinitializesthecustomerobject.
Deposit()–Increasesbalanceamount.
Withdraw()–Checksforminimumbalanceincurrentaccountanddecreasesthebalanceaccordingly.
Display()–Displaysthecustomerdetails.
6.Whatistheuseoftheinit()functionininheritance?Explainthe2waysinwhichitcouldbeinvoked.
7.Whatisthesignificanceofsuper()function?
8.Whatareabstractmethods?HowdoweimplementabstractmethodsinPython.Giveanexample.
9.Findtheoutputofthefollowingcodeandwritethetypeofinheritance:
classperson(object):
def__init__(self,name):
self.name=name
defdisplay(self):
print“Name:”,self.name
classstudent(person):
def__init__(self,name,rollno,marks):
super(student,self).__init__(name)
self.rollno=rollno
self.marks=marks
defdisp(self):
self.display()
print”RollNo:”,self.rollno
print”Marks:”,self.marks
s=student(‘Kali’,11009,78)
s.disp()
10.DefineaclassfurnitureinPythonwiththegivenspecifications:
Instancevariables:Type,Model,
Methods:getType()-ToreturninstancevariableType
getModel()-ToreturninstancevariableModel
show()ToprintinstancevariableTypeandModel
Defineaclasssofa:
No_of_seats,Cost
Methods
getSeats()ToreturninstancevariableNo_of_seats
getCost()ToreturninstancevariableCost
show()ToprintinstancevariableNo_of_seatsandCost
Thisclassinheritsclassfurniture.
Chapter10:Datastructures
Fig10.1:Datastructures
structstudent
{
introllno;
charname[20];
}s;
Lineardatastructure
Alineardatastructuretraversesthedataelementssequentially,inwhichonlyonedataelementcandirectlybereached.Ex:Arrays,LinkedLists
Arrays
Arraysrefertoanamedlistofsimilardataelements.Eachoftheelementscanbereferencedbyindexes.
inta[10];� Referstoanarrayof10integers
Structures
Structurereferstocollectionofvariablesofdifferentdatatypes.
Stacks
Stackdatastructuresrefertothelistsstoredandaccessedinlastinfirstout(LIFO).Insertionsanddeletionstakeplaceatonlyatoneendcalledthetop.
Queues
Queuesarefirstinfirstoutlists,whereinsertionstakeplaceattherearendofthequeuesanddeletionstakeplaceatthefrontend.
LinkedLists
Eachelementiscalledanodeandislinkedtoanotherelement(node).Eachnodehas2partsINFOandPTR.INFOcontainsinformationandPTRisapointertothenextnode.
Non-Lineardatastructure
Everydataitemisattachedtoseveralotherdataitemsinawaythatisspecificforreflectingrelationships.Thedataitemsarenotarrangedinasequentialstructure.Ex:Trees,Graphs.
Trees
Treesaremultileveldatastructureshavingahierarchicalrelationshipamongitselementscallednodes.Topmostnodeiscalledrootofthetreeandbottommostnodesarecalledleavesofthetree.
Graphs
Atreeonlyallowsanodetohavechildren,andtherecannotbeanyloopsinthetree,withamoregeneralgraphwecanrepresentmanydifferentsituations.
Implementationoflistsinmemory
Pythonlistsarearraysofvariablelength.AlistinPythonisanarrayofpointersofaspecificsize.Itoccupies4bytesin32-bitmachineand8bytesin64-bitmachine.
AlgorithmsonListOperations
Traversal
a)Thefor-instatementmakesiteasytoloopovertheitemsinalist:
foriteminL:
printitem
b)Ifweneedboththeindexandtheitem,weusetheenumeratefunction:
forindex,iteminenumerate(L):
printindex,item
c)Ifweneedonlytheindex,userangeandlen:
forindexinrange(len(L)):
printindex
Insertion
appendmethodaddsasingleitemtotheendofthelist
extendmethodaddsitemsfromanotherlist(oranysequence)totheend
insertinsertsanitematagivenindex,andmovetheremainingitemstotheright.
L.append(item)
L.extend(sequence)
L.insert(index,item)
Deletion
Thedelstatementcanbeusedtoremoveanindividualitem,ortoremoveallitemsidentifiedbyaslice.
Thepopmethodremovesanindividualitemandreturnsit
delL[i]
delL[i:j]
item=L.pop()#lastitem
item=L.pop(0)#firstitem
item=L.pop(index)
L.remove(item)
ArraySearching
Alinearsearchlooksdownalist,oneitematatime,withoutjumping.
Program:
Theinoperatorcanbeusedtocheckifanitemispresentinthelist:
ifvalueinL:
print“listcontains”,value
Togettheindexofthefirstmatchingitem,useindex:
i=L.index(value)
Theindexmethoddoesalinearsearch,andstopsatthefirstmatchingitem.Ifnomatchingitemisfound,itraisesaValueErrorexception.
try:
i=L.index(value)
exceptValueError:
i=-1#nomatch
Togettheindexforallmatchingitems,youcanusealoop,andpassinastartindex:
i=-1
try:
while1:
i=L.index(value,i+1)
print“matchat”,i
exceptValueError:
pass
Abinarysearchiswhenwestartwiththemiddleofasortedlist,andseewhetherthat’sgreaterthanorlessthanthevaluewe’relookingfor,whichdetermineswhetherthevalueisinthefirstorsecondhalfofthelist.Jumptothehalfwaythroughthesublist,andcompareagainetc.Thisissimilartohumanstypicallylookupawordinadictionary.
complexity-O(logn)
Program:
defbinary_search(nums,x):
high=len(nums)
low=0
whilelow<high:
mid=(low+high)//2
midval=nums[mid]
ifmidval<x:
low=mid+1
elifmidval>x:
high=mid
else:
returnmid
else:
return-1
#Getthesortedlist
nums=[]
print“Enterthenumberstosortpress-1toquit”
whileTrue:
number=int(raw_input(“Enternumber?”))
ifnumber<>-1:
nums.append(number)
else:
break
nums.sort()
printnums
#CallBinsearchfunction
x=int(raw_input(“Enternumbertobesearched”))
pos=binary_search(nums,x)
ifpos<>-1:
printx,“foundatposition”,pos
else:
printx,“notfound”
ArraySortingBubbleSort
Bubble sort is a simple sorting algorithm that works by repeatedly steppingthrough the list to be sorted, comparing each pair of adjacent itemsand swapping them if they are in the wrong order. The pass through the list isrepeated until no swaps are needed, which indicates that the list is sorted. Thealgorithmgetsitsnamefromthewaysmallerelements“bubble”tothetopofthelist.Because itonlyusescomparisons tooperateonelements, it isacomparison
sort.Althoughthealgorithmissimple,mostotheralgorithmsaremoreefficientforsortinglargelists.
Program:
#BubbleSort
defbubble_Sort(numbers):
i=0
j=0
l=len(numbers)
foriinrange(l):
forjinrange(i,l):
ifnumbers[i]>numbers[j]:
numbers[i],numbers[j]=numbers[j],numbers[i]
print“LISTAFTERSORTING”,numbers
numbers=[90,78,20,46,54,1]
print“LISTBEFORESORTING”,numbers
bubble_Sort(numbers)
names=[‘Neena’,‘Meeta’,‘Geeta’,‘Reeta’,‘Seeta’]
print“LISTBEFORESORTING”,names
bubble_Sort(names)
SelectionSort
Selectionsortperformsthefollowingsteps:1)Startingatindex0,searchtheentirearraytofindthesmallestvalue2)Swapthesmallestvaluefoundwiththevalueatindex03)Repeatsteps1&2startingfromthenextindex
Inotherwords,we’regoingtofindthesmallestelementinthearray,andputitinthefirstposition.Thenwe’regoingtofindthenextsmallestelement,andputitinthesecondposition.Thisprocesswillberepeateduntilwerunoutofelements.Hereisanexampleofthisalgorithmworkingon5elements.Let’sstartwithasamplearray:
{30,50,20,10,40}
First,wefindthesmallestelement,startingfromindex0:
{30,50,20,10,40}
Wethenswapthiswiththeelementatindex0:
{10,50,20,30,40}
Nowthatthefirstelementissorted,wecanignoreit.Consequently,wefindthesmallestelement,startingfromindex1:
{10,50,20,30,40}
Andswapitwiththeelementinindex1:
{10,20,50,30,40}
Findthesmallestelementstartingatindex2:
{10,20,50,30,40}
Andswapitwiththeelementinindex2:
{10,20,30,50,40}
Findthesmallestelementstartingatindex3:
{10,20,30,50,40}
Andswapitwiththeelementinindex3:
{10,20,30,40,50}
Finally,findthesmallestelementstartingatindex4:
{10,20,30,40,50}
Andswapitwiththeelementinindex4(nochange)
{10,20,30,40,50}
Program:
defSelSort(nums):
n=len(nums)
#Findthesmallestiteminnums[0]…nums[n-1]
foriinrange(n-1):
pointer=i
forjinrange(i+1,n):
if(nums[j]<nums[pointer]):
pointer=j
#swap
nums[i],nums[pointer]=nums[pointer],nums[i]
print“Listaftersorting”
printnums
nums=[]
sortedlist=[]
print“Enterthenumberstosortpress-1toquit”
whileTrue:
number=int(raw_input(“Enternumber?”))
ifnumber<>-1:
nums.append(number)
else:
break
print“Listbeforesorting”
printnums
#Callselectionsortmethod
SelSort(nums)
InsertionSort
Every repetition of insertion sort removes an element from the input data,inserting it into the correct position in the already-sorted list, until no inputelements remain. The choice of which element to remove from the input isarbitraryandcanbemadeusingalmostanychoicealgorithm.It’sthesamestrategythatweuseforsortingourbridgehand.Wepickupacard,startatthebeginningofourhandandfindtheplacetoinsertthenewcard,insertitandmovealltheothersuponeplace.
Program:
definsertion_sort(numbers):
forKinrange(1,len(numbers)):
temp=numbers[K]
ptr=K-1
while(ptr>=0)andnumbers[ptr]>temp:
numbers[ptr+1]=numbers[ptr]
ptr=ptr-1
numbers[ptr+1]=temp
printnumbers
numbers=[15,-5,20,-10,10]
print“LISTBEFORESORTING”,numbers
insertion_sort(numbers)
Stacks
AstackisadatastructurethatallowsaddingandremovingelementsaccordingtotheLast-InFirst-Out(LIFO)principle.Everytimeanelementisadded,itgoesonthetopofthestack;theonlyelementthatcanberemovedistheelementthatwasatthetopofthestack.
Theoperationsperformedonthestackare:
Push:Adding(inserting)newelementontothestack.
Pop:Removing(deleting)anelementfromthestack
Traversal:Printingelementsofthestack
Addingnewelementtothestacklistiscalledpushoperation.Whenthestackisempty,thevalueoftopis-1.Basically,anemptystackisinitializedwithaninvalidsubscript.WheneveraPushoperationisperformed,thetopisincrementedbyoneandthenthenewvalueisinsertedonthetopofthelisttillthetimethevalueoftopislessthanorequaltothesizeofthestack.
Removingexistingelementsfromthestacklistiscalledpopoperation.Herewehavetocheckifthestackisemptybycheckingthevalueoftop.Ifthevalueoftopis-1,thenthestackisemptyandsuchasituationiscalledUnderflow.OtherwisePopoperationcanbeperformedinthestack.Thetopisdecrementedbyoneifanelementisdeletedfromthelist.
Traversalismovingthroughtheelementsofthestack.Ifyouwanttodisplayalltheelementsofthestack,thealgorithmwillbeasfollows:
InPython,pop()andappend()functionsaretheresothereisnoneedtowritethecodetoaddandremoveelementsinthestack.ConsiderthefollowingprogramsthatperformthePushandPopoperationonthestackthroughappend()andpop().
Program
stack=[]
choice=3
whilechoice<>5:
choice=int(raw_input(“1-CREATE2-PUSH3-POP4-VIEW5-EXIT”))
ifchoice==1:
print“CreatingStack”
whileTrue:
print“EntertheelementsofStackenter-1whendone”
n=int(raw_input(“Enterelement?”))
ifn<>-1:
stack.append(n)
else:
break
elifchoice==2:
ch=‘y’
print“PerformingPUSH”
whilech==‘y’:
n=int(raw_input(“Enternumbertobeinserted?”))
stack.append(n)
ch=raw_input(“Aretheremorenumbers?y-yesn-no”)
elifchoice==3:
ch=‘y’
print“PerformingPOP”
whilech==‘y’:
stack.pop()
ch=raw_input(“ContinuePopping?y-yesn-no”)
elifchoice==4:
print“STACKCONTENTSARE”
printstack
else:
break
Applicationofstacks1. Expressionevaluation
2. Backtracking(gameplaying,findingpaths,exhaustivesearching)
3. Memorymanagement,run-timeenvironmentfornestedlanguagefeatures.
Expressionevaluation
Weareaccustomedtowritearithmeticexpressionswiththeoperationbetweenthetwooperands:a+borc/d.Ifwewritea+b*c,however,wehavetoapplyprecedencerulestoavoidtheambiguousevaluation(addfirstormultiplyfirst?).Postfixexpressionsareeasilyevaluatedwiththeaidofastack.
PostfixEvaluationAlgorithm
Assumewehaveastringofoperandsandoperators,aninformal,byhandprocessis
1.Scantheexpressionlefttoright
2. Skipvaluesorvariables(operands)
3. Whenanoperatorisfound,applytheoperationtotheprecedingtwooperands
4. Replacethetwooperandsandoperatorwiththecalculatedvalue(threesymbols
arereplacedwithoneoperand)
5. Continuescanninguntilonlyavalueremains—theresultoftheexpression
Letusseehowtheabovealgorithmwillbeimplementedusinganexample.
Example:AB+C*D/
IfA=2,B=3,C=4,D=5
InfixtransformationtoPostfix
Thisprocessusesastack.Wehavetoholdinformationthat’sexpressedinsideparentheseswhilescanningtofindtheclosing‘)’.Wealsohavetoholdinformationonoperationsthatareoflowerprecedenceonthestack.
Thealgorithmis:
1.Createanemptystackandanemptypostfixoutputstring/stream
2. Scantheinfixinputstring/streamlefttoright
3. Ifthecurrentinputtokenisanoperand,simplyappendittotheoutputstring(notetheexamplesabovethattheoperandsremaininthesameorder)
4. Ifthecurrentinputtokenisanoperator,popoffalloperatorsthathaveequalorhigherprecedenceandappendthemtotheoutputstring;pushtheoperatorontothestack.Theorderofpoppingistheorderintheoutput.
5. Ifthecurrentinputtokenis‘(‘,pushitontothestack
6. Ifthecurrentinputtokenis‘)’,popoffalloperatorsandappendthemtotheoutputstringuntila‘(‘ispopped;discardthe‘(‘.
7. Iftheendoftheinputstringisfound,popalloperatorsandappendthemtotheoutputstring.
Thisalgorithmdoesn’thandleerrorsintheinput,althoughcarefulanalysisofparenthesisorlackofparenthesiscouldpointtosucherrordetermination.
Example:ConvertA+(B*C–(D/E^F)*G)*Hintopostfixformshowingstackstatusaftereverystepintabularform
S.No Element Stack Expression
1 A ( A
2 + (+ A
3 ( (+( A
4 B (+( AB
5 * (+(* AB
6 C (+(* ABC
7 - (+(- ABC*
8 ( (+(-( ABC*
9 D (+(-( ABC*D
10 / (+(-(\ ABC*D
11 E (+(-(\ ABC*DE
12 ^ (+(-(\^
ABC*DE
13 F (+(-(\^
ABC*DEF
14 ) (+(- ABC*DEF^/
15 * (+(-* ABC*DEF^/
16 G (+(-* ABC*DEF^/G
17 ) (+ ABC*DEF^/G*-
18 * (+* ABC*DEF^/G*-
19 H (+* ABC*DEF^/G*-H
20 ) ABC*DEF^/G*-H*+
Queue
Queueisafirst-in,first-out(FIFO)datastructure.i.e.theelementaddedfirsttothequeuewillbetheonetoberemovedfirst.Elementsarealwaysaddedtotherearofthequeueandremovedfromthefrontofthequeue.
Iffront=0,thenqueueisempty
Theno.ofelementsinthequeueisgivenby
N=front–rear+1
Program:
queue=[]
choice=3
whilechoice<>5:
choice=int(raw_input(“1-CREATE2-INSERT3-DELETE4-VIEW5-EXIT”))
ifchoice==1:
print“CreatingQueue”
whileTrue:
print“EntertheelementsofQueueenter-1whendone”
n=int(raw_input(“Enterelement?”))
ifn<>-1:
queue.append(n)
else:
break
elifchoice==2:
ch=‘y’
print“PerformingINSERT”
whilech==‘y’:
n=int(raw_input(“Enternumbertobeinserted?”))
queue.append(n)
ch=raw_input(“Aretheremorenumbers?y-yesn-no”)
elifchoice==3:
ch=‘y’
print“PerformingDELETE”
whilech==‘y’:
queue.pop(0)
ch=raw_input(“Continuedelete?y-yesn-no”)
elifchoice==4:
print“QUEUECONTENTSARE”
printqueue
else:
break
Deque(Double-endedqueues)
Dequesare the refined queueswhich allows insertions and deletions at bothendsofthelist.Theyareof2types
Inputrestricteddeques–allowsinsertionsatoneendonly
Outputrestricteddeques–allowsdeletionsatoneendonly
CircularQueues
Circular Queues are the queues implemented in circular form rather than astraightline.Thecircularqueueconsidersitselfcontiguousatoppositeends.Thatiswhy if space is there in the beginning, the rear shifts back to beginning afterreachingthemaxsize.
SolvedExamples
1.Defineadatastructure.
Ans.Adatastructureisagroupofdatawhichcanbeprocessedasasingleunit.Thisgroupofdatamaybeofsimilarordissimilardatatypes.DataStructuresareveryusefulwhileprogrammingbecausetheyallowprocessingoftheentiregroupofdataasasingleunit.
2.GiveonepointofdifferencebetweenanarrayandalistinPython.
Ans.Anarrayisdefinedasasetofcontiguousdataofsimilardatatype.Pythonlistsareactuallyarraysofvariablelength.Theelementsofalistareofheterogeneoustypeswhichmeanstheyareofdifferentdatatypes
3.HowismemoryallocatedtoalistinPython?
Ans.AlistinPythonisanarraythatcontainselements(pointerstoobjects)ofaspecificsizeonlyandthisisacommonfeatureofalldynamicallytypedlanguages.Forimplementationofalist,acontiguousarrayofreferencestootherobjectsisused.Pythonkeepsapointertothisarrayandthearray’slengthisstoredinalistheadstructure.Thismakesindexingofalistindependentofthesizeofthelistorthevalueoftheindex.Whenitemsareappendedorinserted,thearrayofreferencesisresized.
4.Howislinearsearchdifferentfrombinarysearch?
Ans.
Binarysearchrequirestheinputdatatobesorted;linearsearchdoesn’t
Binarysearchrequiresanorderingcomparison;linearsearchonlyrequiresequalitycomparisons
BinarysearchhascomplexityO(logn);linearsearchhascomplexityO(n)asdiscussedearlier
Binarysearchrequiresrandomaccesstothedata;linearsearchonlyrequiressequentialaccess(thiscanbeveryimportant-itmeansalinearsearchcanstreamdataofarbitrarysize)
5.Writeaprogramtogetalistofnumbersandanumbertobesearchedandprintitspositioninthelist.
Ans.
maxrange=input(“EnterCountofnumbers:“)
marks=[]
flag=False
foriinrange(0,maxrange):
marks.append(input(“?”))
number=input(“Enternumbertobesearched”)
foriinrange(0,maxrange):
ifmarks[i]==number:
printnumber,“foundatposition”,i
flag=True
ifflag==False:
printnumber,“notfoundinlist”
6.Writeafunctionthattakesalistthatissortedinascendingorderandanumberasarguments.Thefunctionshoulddothefollowing:
a.Insertthenumberpassedasargumentinasortedlist.
b.Deletethenumberfromthelist.
Ans.
frombisectimportbisect
deflistfunc(sortedlist,number):
insert_point=bisect(sortedlist,number)
sortedlist.insert(insert_point,number)
print“ListafterInsertion”
printsortedlist
sortedlist.remove(number)
print“ListafterDeletion”
printsortedlist
maxrange=input(“EnterCountofnumbers:“)
numlist=[]
flag=False
foriinrange(0,maxrange):
numlist.append(input(“?”))
numlist.sort()
number=input(“Enterthenumber”)
listfunc(numlist,number)
7.Writeafunctionforbinarysearch.
Ans.
defbinary_search(SORTEDLIST,number):
low=0
high=len(SORTEDLIST)
found=False
while(low<high)andfound==False:
mid=(int)(low+high/2)
ifSORTEDLIST[mid]==number:
print“Numberfoundat”,mid
found=True
break
elifSORTEDLIST[mid]<number:
low=mid+1
else:
high=mid-1
iflow>=high:
print“Numbernotfound”
maxrange=input(“EnterCountofnumbers:“)
numlist=[]
foriinrange(0,maxrange):
numlist.append(input(“?”))
numlist.sort()
print“Sortedlist”,numlist
number=input(“Enterthenumber”)
binary_search(numlist,number)
8.Inthefollowinglistcontainingintegers,sortthelistusingInsertionsortalgorithm.Alsoshowthestatusofthelistaftereachiteration.
10,-2,6,-1,5
Ans.
definsertion_sort(NUMLIST):
forKinrange(1,len(NUMLIST)):
temp=NUMLIST[K]
ptr=K-1
while(ptr>=0)andNUMLIST[ptr]>temp:
NUMLIST[ptr+1]=NUMLIST[ptr]
ptr=ptr-1
NUMLIST[ptr+1]=temp
printNUMLIST
NUMLIST=[10,-2,6,-1,5]
print“LISTBEFORSORTING”,NUMLIST
insertion_sort(NUMLIST)
LISTBEFORSORTING[10,-2,6,-1,5]
[-2,10,6,-1,5]
[-2,6,10,-1,5]
[-2,-1,6,10,5]
[-2,-1,5,6,10]
9. Writeaprogramtosortalistcontainingnamesofstudentsinascendingorder
usingselectionsort.
Ans.
defselection_sort(NUMLIST):
foriinrange(0,len(NUMLIST)):
min=i
forjinrange(i+1,len(NUMLIST)):
ifDATA_LIST[j]<NUMLIST[min]:
min=j
#swapping
temp=NUMLIST[min]
NUMLIST[min]=NUMLIST[i]
NUMLIST[i]=temp
printNUMLIST
NAME_LIST=[‘Neena’,‘Beeta’,‘Reeta’,‘Geeta’,‘Seeta’]
print“LISTBEFORESORTING”,NAME_LIST
selection_sort(NAME_LIST)
LISTBEFORESORTING[‘Neena’,‘Beeta’,‘Reeta’,‘Geeta’,‘Seeta’]
[‘Beeta’,‘Neena’,‘Reeta’,‘Geeta’,‘Seeta’]
[‘Beeta’,‘Geeta’,‘Reeta’,‘Neena’,‘Seeta’]
[‘Beeta’,‘Geeta’,‘Neena’,‘Reeta’,‘Seeta’]
[‘Beeta’,‘Geeta’,‘Neena’,‘Reeta’,‘Seeta’]
[‘Beeta’,‘Geeta’,‘Neena’,‘Reeta’,‘Seeta’]
10.Considerthefollowingunsortedlist
90782046541
Writethelistafter:
a.3rditerationofselectionsort
b.4thiterationofbubbleort
c.5thiterationofinsertionsort
Ans.
Working
Bubblesort SelectionSort Insertionsort
[1,90,78,46,54,20]
[1,20,90,78,54,46]
[1,20,46,90,78,54]
[1,20,46,54,90,78]
[1,20,46,54,78,90]
[1,20,46,54,78,90]
[1,78,20,46,54,90]
[1,20,78,46,54,90]
[1,20,46,78,54,90]
[1,20,46,54,78,90]
[1,20,46,54,78,90]
[1,20,46,54,78,90]
[78,90,20,46,54,1]
[20,78,90,46,54,1]
[20,46,78,90,54,1]
[20,46,54,78,90,1]
[1,20,46,54,78,90]
a.3rditerationofselectionsort:[1,20,46,78,54,90]
b.4thiterationofbubblesort:[1,20,46,54,90,78]
c.5thiterationofinsertionsort:[1,20,46,54,78,90]
11.Expandthefollowing:
(i)LIFO(ii)FIFO
Ans.
LIFO:Last-InFirst-Out
FIFO:First-InFirst-Out
12.Whatisstack?
Ans. A stack is a data structure that allows adding and removing elements in aparticularorder.Everytimeanelementisadded,itgoesonthetopofthestack;theonlyelementthatcanberemovedistheelementthatwasatthetopofthestack.
13.WhatisQueue?
Ans.Queueisafirst-in,first-out(FIFO)datastructure.i.e.theelementaddedfirsttothequeuewillbetheonetoberemovedfirst.Elementsarealwaysaddedtotherearofthequeueandremovedfromthefrontofthequeue.
14.Giveoneexampleeachofinfix,postfixandprefixexpression.
Ans.
Infix:A+B*C/D
Postfix:ABC*D/+
Prefix:+/*BCDA
15.Whatistheadvantageofpostfixexpressions?
Ans:Aninfixexpressionisdifficultforthemachinetoknowandkeeptrackofprecedenceofoperators.Apostfixexpressionitselfdeterminestheprecedenceofoperatorssoitiseasierforthemachinetocarryoutapostfixexpressionthananinfixexpression.
16.Whataretheadvantagesofcircularqueues?
Ans:Incircularqueuesmemoryisutilizedefficiently.Inqueuewhenwedeleteanyelementonlyfrontincrementsby1butthatpositionisnotusedlater.Whenweperformmoreaddanddeleteoperationmemorywastageincreases.Butincircularqueuememoryisutilizedifwedeleteanyelementthatpositionisusedlaterbecauseitiscircular.
17.Considerthefollowingcircularqueuewithacapacityof6elements:Front=2rear=4;
Describethequeueasthefollowingoperationstakeplace.
a)AddD,E
b)Delete2letters
c)AddX,Y,Z
Ans:
a)Front=2Rear=6
b)Front=4Rear=6
c)Front=4Rear=(6+3)mod6=3
18.EvaluatethefollowingBooleanpostfixexpressionshowingstackstatusaftereverystep:True,False,True,AND,OR,False,NOT,AND
Ans:
19.Evaluateusingstack10,3,*,30,2,*,-
Ans.
20.ConvertA+(B*C–(D/E^F)*G)*Hintopostfixformshowingstackstatusaftereverystep.
S.No Element Stack Expression
1 A ( A
2 + (+ A
3 ( (+( A
4 B (+( AB
5 * (+(* AB
6 C (+(* ABC
7 - (+(- ABC*
8 ( (+(-( ABC*
9 D (+(-(
ABC*D
10 / (+(-(\
ABC*D
11 E (+(-(\
ABC*DE
12 ^ (+(-(\^
ABC*DE
13 F (+(-(\^
ABC*DEF
14 ) (+(- ABC*DEF^/
15 * (+(-*
ABC*DEF^/
16 G (+(-*
ABC*DEF^/G
17 ) (+ ABC*DEF^/G*-
18 * (+* ABC*DEF^/G*-
19 H (+* ABC*DEF^/G*-H
20 ) ABC*DEF^/G*-H*+
21.Whataretheapplicationsofqueueincomputer?
Ans.
1. Inasingleprocessormultitaskingcomputer,job(s)waitingtobeprocessedformaqueue.Samehappenswhenweshareaprinterwithmanycomputers.
2. CompilingaHLLcode3. Usingdownloadmanager,formultiplefilesalsousesqueuefororderingthefiles.4. InmultiuserOS-jobschedulingisdonethroughqueue.
22.Writeafunctiontopushanystudent’sinformationtostack.
Ans.
defpush(stack):
s=[]
print“STACKBEFOREPUSH”
display(stack)
s.append(input(“Enterstudentrollno?”))
s.append(raw_input(“Enterstudentname”))
s.append(raw_input(“Enterstudentgrade”))
stack.append(s)
defdisplay(stack):
l=len(stack)
print“STACKCONTENTS”
foriinrange(l-1,-1,-1):
printstack[i]
stack=[]
print“CreatingStack”
n=input(“Enterthenumberofstudents”)
foriinrange(n):
student=[]
student.append(input(“Enterstudentrollno?”))
student.append(raw_input(“Enterstudentname”))
student.append(raw_input(“Enterstudentgrade”))
stack.append(student)
push(stack)
display(stack)
23.Writethepushoperationofstackcontainingnamesusingclass.
Ans.
classstack:
s=[]
defpush(self):
a=raw_input(“Enteranyname:”)
stack.s.append(a)
defdisplay(self):
l=len(stack.s)
foriinrange(l-1,-1,-1):
printstack.s[i]
a=stack()
n=input(“Enterno.ofnames”)
foriinrange(n):
a.push()
a.display()
24.Writethepopoperationofstackcontainingnamesusingclass.
Ans.
classstack:
s=[]
defpush(self):
a=raw_input(“Enteranyname:”)
stack.s.append(a)
defpop(self):
if(a.s==[]):
print“StackEmpty”
else:
print“Deletedelementis:“,a.s.pop()
defdisplay(self):
l=len(stack.s)
print“STACKCONTENTS”
foriinrange(l-1,-1,-1):
printstack.s[i]
a=stack()
n=input(“Enterno.ofnames”)
foriinrange(n):
a.push()
a.pop()
a.display()
25. Writeafunctiontoaddanycustomer’sinformationtoqueue.
Ans.
definsert(queue):
customer=[]
print“QUEUEBEFOREINSERT”
display(queue)
customer.append(input(“Entercustomernumber?”))
customer.append(raw_input(“Entercustomername”))
customer.append(input(“Entercustomerphonenumber”))
queue.append(customer)
defdisplay(queue):
l=len(queue)
foriinrange(0,l):
printqueue[i]
queue=[]
print“CreatingQueue”
n=input(“Enterthenumberofcustomers”)
foriinrange(n):
customer=[]
customer.append(input(“Entercustomernumber?”))
customer.append(raw_input(“Entercustomername”))
customer.append(input(“Entercustomerphonenumber”))
queue.append(customer)
insert(queue)
display(queue)
26.Writethedeletionoperationofqueuecontainingnumbersusingclass.
Ans.
classqueue:
s=[]
definsert(self):
a=input(“Enterthenumber:”)
queue.s.append(a)
defdelete(self):
if(a.s==[]):
print“QueueEmpty”
else:
print“Deletedelementis:“,queue.s[0]
delqueue.s[0]
defdisplay(self):
l=len(queue.s)
print“QUEUECONTENTS”
foriinrange(0,l):
printqueue.s[i]
a=queue()
n=input(“Enterno.ofnumbers”)
foriinrange(n):
a.insert()
a.delete()
a.display()
PracticeQuestions1. Writeaprogramtosortalistofitemsusingbubblesort.Useclassestostoreitem
details.2. Writeapythonprogramtosortalistofnumbersusinginsertionsortalgorithm.
3.Convertthefollowinginfixexpressiontoitsequivalentpostfixexpressionshowingstackcontentsfortheconversion:
a)A+B*(C–D)/E^F
b)(A+B)*(C^(D-E)+F)-G
4.Evaluatethefollowingpostfixnotationofexpression:(Showstatusofstackafterexecutionofeachoperation):
a)20,30,+,50,40,-,*
b)5,20,15,-,*,25,2,*,+
5.WriteacompleteprograminPythontoimplementadynamicallyallocatedqueuecontainingnamesofcities.
6.Writethepopoperationofstackcontainingnumbersusingclass.
7.Writeaprogramtomaintainastackofbooks.
8. Writeaprogramtosimulateareservationqueueusingclasses.
Chapter11:DATAFILEHANDLING
Wehavedonealotofprogrammingwherewehavestoreddatainlistsordictionaries.Thedataenteredisstoredinprimarymemorywhichisatemporarymemory.
Let’ssayforexamplethatwearegeneratingastudent’sreportcard.Itwouldbeniceifthedataisstoredinpermanentstorage.Filesareusedtostoredatapermanently.Afileisabunchofbytesstoredonsomestoragedeviceliketape,magneticdisketc.Thereare2typesoffiles.
TextfileisafilethatstoresinformationinASCIIcharacters.Intextfiles,eachline of text is terminatedwith a special character known as EOL (End of Line)characterordelimitercharacter.WhenthisEOLcharacterisreadorwritten,certaininternaltranslationstakeplace.
Binaryfileisafilethatcontainsinformationinthesameformatasitisheldinmemory.Inbinaryfiles,nodelimitersareusedforalineandnotranslationsoccurhere.So,binaryfilesarefasterandoccupylesserstoragespace.
OpenFunction
Itcreatesafileobjectwhichwouldbeutilizedtocallothersupportmethodsassociatedwithit.
fileobject=open(filename[,access_mode][,buffering])
filename:Thefile_nameargumentisastringvaluethatcontainsthenameofthefilethatyouwanttoaccess.
access_mode:Theaccess_modedeterminesthemodeinwhichthefilehastobeopenedie.read,writeappendetc.Acompletelistofpossiblevaluesisgivenbelowinthetable.Thisisoptionalparameterandthedefaultfileaccessmodeisread(r)
buffering:Ifthebufferingvalueissetto0,nobufferingwilltakeplace.Ifthebufferingvalueis1,linebufferingwillbeperformedwhileaccessingafile.Ifyouspecifythebufferingvalueasanintegergreaterthan1,thenbufferingactionwillbeperformedwiththeindicatedbuffersize.Ifnegative,thebuffersizeisthesystemdefault(defaultbehavior).
FileopeningModes
Modes Description
r Opensafileforreadingonly.Thefilepointerisplacedatthebeginningofthefile.Thisisthedefaultmode.
rb Opensafileforreadingonlyinbinaryformat.Thefilepointerisplacedatthebeginningofthefile.Thisisthedefaultmode.
r+ Opensafileforbothreadingandwriting.Thefilepointerwillbeatthebeginningofthefile.
rb+ Opensafileforbothreadingandwritinginbinaryformat.Thefilepointerwillbeatthebeginningofthefile.
w Opensafileforwritingonly.Overwritesthefileifthefileexists.Ifthefiledoesnotexist,
createsanewfileforwriting.
wb Opensafileforwritingonlyinbinaryformat.Overwritesthefileifthefileexists.Ifthefiledoesnotexist,createsanewfileforwriting.
w+ Opensafileforbothwritingandreading.Overwritestheexistingfileifthefileexists.Ifthefiledoesnotexist,createsanewfileforreadingandwriting.
wb+ Opensafileforbothwritingandreadinginbinaryformat.Overwritestheexistingfileifthefileexists.Ifthefiledoesnotexist,createsanewfileforreadingandwriting.
a Opensafileforappending.Thefilepointerisattheendofthefileifthefileexists.Thatis,thefileisintheappendmode.Ifthefiledoesnotexist,itcreatesanewfileforwriting.
ab Opensafileforappendinginbinaryformat.Thefilepointerisattheendofthefileifthefileexists.Thatis,thefileisintheappendmode.Ifthefiledoesnotexist,itcreatesanewfileforwriting.
a+ Opensafileforbothappendingandreading.Thefilepointerisattheendofthefileifthefileexists.Thefileopensintheappendmode.Ifthefiledoesnotexist,itcreatesanewfileforreadingandwriting.
ab+ Opensafileforbothappendingandreadinginbinaryformat.Thefilepointerisattheendofthefileifthefileexists.Thefileopensintheappendmode.Ifthefiledoesnotexist,it
createsanewfileforreadingandwriting.
Thefileobjectatrributes
Oncea file isopenedandyouhaveone fileobject,youcangetvarious informationrelatedtothatfile.Hereisalistofallattributesrelatedtofileobject:
Attribute Description
file.closed Returnstrueiffileisclosed,falseotherwise.
file.mode Returns access mode with which file wasopened.
file.name Returnsnameofthefile.
file.softspace Returns false if space explicitly required withprint,trueotherwise.
Openingafile
Method1:
file=open(“Test.txt”,“r+”)
willopenafilecalledTest.txtforreadingandwritingpurpose.
Wecanuseavariableinsteadofaconstantasnameofthefile.
filename=raw_input(“Enterfilename”)
File=open(filename,“r”)
Thefilehastobeinthesamefolderwhereweareworkingnow,otherwisewehavetospecifythecompletepath.
Method2:
F=file(“Test”,”w”)
Method3:
withstatementcanalsobeusedforsamepurpose.Usingwithensuresthatalltheresourcesallocatedtofileobjectsgetsdeallocatedautomaticallyoncewestopusingthefile.Itssyntaxis:
withopen()asfileobject:
Example:
withopen(“Test.txt”,“r+”)asfile:
……………..
FileMethods
S.No Methods Description Example
1 close() Closethefile. fileobject.close()
2 flush()
Flushtheinternalbuffer
fileobject.flush()
3 next()
Returnsthenextlinefromthefileeachtimeitisbeingcalled.
fileobject.next()
4 read([size]) Readsatmostsizebytesfromthefile
X=fileobject.read([size])
5 readline([size])
Readsoneentirelinefromthefile.Atrailingnewlinecharacteriskeptinthestring.
X=fileobject.readline()
6 readlines([size]) ReadsuntilEOFusingreadline()andreturnalistcontainingthelines.Ifsizehintargumentispresent,lines
X[]=fileobject.readlines()
totallingapproximatelysizehintbytesareread.
7 seek(offset[,pos])
Setsthefile’scurrentposition.
fileobject.seek(5)
8 tell()
Returnsthefile’scurrentposition
fileobject.tell()
9 truncate([size])
Truncatesthefile’ssize.
fileobject.truncate()
10 write(str)
Writesastringtothefile.
str=“Hello”
fileobject.write(str)
11 writelines(sequence)
Writesasequenceofstringstothefile.
strlist=[‘I’,‘love’,‘Python’]
Fileobject.writelines(strlist)
Fromtheabovetableonfilemethods,readlines()willgetallthelinesofthefileasalist(orsequence).Towriteinafileweusewriteandwritelinesmethod.
osmodulefunctionsSomeoftheusefulmethods,whichcanbeusedwithfilesinosmoduleareasfollows:
1.getcwd()–givesthenameofcurrentworkingdirectory
2.path.abspath(filename)-givesusthecompletepathnameofthedatafile.
3.path.isfile(filename)-checkswhetherthefileexistsornot.
4.remove(filename)-deletesthefile.
5.rename(filename1,filename2)-changesthenameoffilename1withfilename2.
Operationsontextfiles
Writing/Creatingatextfile
file=open(“input.txt”,’w’)
whileTrue:
line=raw_input(“Entertheline”)
file.write(line)
choice=raw_input(“Doyouhavemorelines?YorN”)
ifchoice==‘N’:
break
file.close()
Theabovecodewouldcreateafile“input.txt”.Itwouldgetlinesfromtheuserandwriteitintothefile.
Readingfromatextfile
file=open(“input.txt”,’r’)
lines=file.readlines()
file.close()
forlineinlines:
printline
Theabovecodewouldopenthefileandreadtheentirecontentsofthefileintothelist–lines.Wecanthenuseaforlooptoprintthecontentsofthelist.
Traversal/Display
forlineinopen(“story.txt”,“r”).readlines():
printline
file.close()
Deletion
withopen(‘story.txt’,‘r’)asfile:
l=file.readlines()
file.close()
printl
lineno=input(“Enterthelinenumbertobedeleted”)
dell[lineno]
printl
file.open(‘story.txt’,‘w’)
file.writelines(l)
file.close()
Updation
withopen(“data.txt”,“r”)asfile:
contents=file.readlines()
file.close()
i=0
forlineincontents:
printline
ch=raw_input(“Doyouwanttochangethisline?”)
ifch==‘Y’:
newline=raw_input(“Enterthenewline”)
contents[i]=newline
i=i+1
withopen(“data.txt”,“w”)asfile:
file.writeline(contents)
printcontents
RandomAccess
tell()methodreturnsanintegergivingthecurrentpositionofobjectinthefile.Theintegerreturnedspecifiesthenumberofbytesfromthebeginningofthefiletillthecurrentpositionoffileobject.
Syntax:f.tell()
seek()methodcanbeusedtopositionthefileobjectatparticularplaceinthefile.
Syntax:f.seek(offset[,pos])
hereoffsetisusedtocalculatethepositionoffileobjectinthefileinbytes.Offsetisaddedtopos(referencepoint)togettheposition.Followingisthelistofposvalues:
Valuereferencepoint
0beginningofthefile
1currentpositionoffile
2endoffile
defaultvalueofposis0,i.e.beginningofthefile
Example:
>>>f.tell()#getthecurrentfileposition
34
>>>f.seek(0)#bringfilecursortoinitialposition
0
>>>print(f.read())#readtheentirefile
ThisisaPythonfile
Thisexplainsabout
seek()
tell()
Binaryfiles
Serializationistheprocessofconvertingadatastructure/objectthatcanbestoredinnonstringformatandcanberesurrectedlater.Serializationcanalsobecalledasdeflatingthedataandresurrectingasinflatingit.
Picklemoduleisusedinserializationofdata.Itallowustostoredatainbinaryforminthefile.Dumpandloadfunctionsareusedtowritedataandreaddatafromfile.
Writinginabinaryfile
importpickle#step1
file=open(‘data.dat’,‘wb’)#step2
whileTrue:
x=int(raw_input(“Enternumber”))#step3
pickle.dump(x,file)#step4
ans=raw_input(‘wanttoentermoredataY/N’)
ifans.upper()==‘N’:break
file.close()#step5
Readingfromabinaryfile
importpickle#step1
file=open(‘data.dat’,‘rb’)#step2
try:
whileTrue:
y=load(file)#step3
printy#step4
exceptEOFError:#Endoffileerror
pass
file.close()#step5
BinaryfileManipulation
Letustakeanexampleofaninventorysystem.Weneedtoimporttherequiredmodules
frompickleimportload,dump
importos
importsys
Thenextstepistocreatetheclasswiththerequiredattributes.Inthiscase,weneedtocreateanitemclasswithattributeslikeiemcode,itemname,priceandqty.Wehavealsodefinedthegetanddisplayfunctions.
classITEM:
def__init__(self):
self.itemcode=0
self.itemname=”
self.price=0.0
self.qty=0
defget(self):
self.itemcode=input(“Enteritemcode”)
self.itemname=raw_input(“Enteritemname”)
self.price=float(raw_input(“Enterprice”))
self.qty=input(“Enterquantity”)
defdisplay(self):
print“ItemCode”,self.itemcode
print“ItemName”,self.itemname
print“Price”,self.price
print“Quantity”,self.qty
Letusdefinethefilename
fname=‘ITEM.dat’
choice=0
whilechoice<5:
choice=input(“1-create2-display3-search4-update5-exit”)
ifchoice==1:
ofile=open(fname,‘wb’)
print‘Goingtodump’
num=input(“Enternumberofitems”)
foriinrange(num):
t=ITEM()
t.get()
dump(t,ofile)
ofile.close()
print“Writtenintofile”
Weopenthefilein‘wb’-writebinarymode.Wecalltheget()functiontogetallthedetailsoftheitemfromtheuser.Eachitemisthenwrittenintothefileusingthedump()function.
elifchoice==2:
ifnotos.path.isfile(fname):
print“filedoesnotexist”
else:
ifile=open(fname,‘rb’)
try:
whileTrue:
t=load(ifile)
t.display()
exceptEOFError:
pass
ifile.close()
Fordisplayingthewrittencontentsfromthefile,weopenthefilein‘rb’readbinarymode.Theloadfunctiongetstheitemfromthefileandweusethedisplay()functiontodisplaytheitem.Inasimilarway,tilltheend-of-fileallthecontentsaredisplayedonthescreen.
elifchoice==3:
ifile=open(fname,‘rb’)
search=input(“Enteritemcode”)
try:
whileTrue:
t=load(ifile)
ift.itemcode==search:
t.display()
exceptEOFError:
pass
ifile.close()
Tosearchforaparticularitem,
1. Gettheitemcodetobesearched.2. Openthefileinreadmode.
3. Gettheitem4. Iftheitemcode=theitemtobesearchedthedisplaythedetailsoftheitemlike
itemname,priceandquantityordered5. Repeatsteps3&4tillwereachtheendoffile6. Closethefile
elifchoice==4:
ifile=open(fname,‘rb+’)
search=input(“Enteritemcode”)
try:
whileTrue:
#Storethepositionofthefirstbyteofline
pos=ifile.tell()
t=load(ifile)
ift.itemcode==search:
t.itemname=raw_input(“Enternewitemname”)
t.price=float(raw_input(“Enternewprice”))
t.qty=input(“Enternewquantity”)
#Movethefilepointertothestoredposition
ifile.seek(pos)
dump(t,ifile)
print“Updated”
break
exceptEOFError:
pass
Tomodifyafile,
1. Openthefilein‘rb+’modewhichenablesbothreading&writing2. Gettheitemcodetobemodified
3. Storethepositionofthefirstbyte4. Gettheitem5. Ifitemcode=itemtobemodifiedthen
a)getthenewdetails
b)Movethefilepointertothestartingofthisline
c)Writethenewdetails(Overwrite)
6. Closethefile
else:
break
SolvedQuestions1. Whatistheuseofread()function?
Ans.Itreadsthewholefileandreturnsthewholethinginastring
2. Whatistheuseofreadline()function?
Ans.readsthefirstlineofthefileandreturnsitasastring
3. Whatistell()method?
Ans.Thetell()methodtellsyouthecurrentpositionwithinthefileinotherwords,thenextreadorwritewilloccuratthatmanybytesfromthebeginningofthefile
4. Whatistheuseofrename()function?
Ans.The rename()method takes two arguments, the current filename and the newfilename.
os.rename(current_file_name,new_file_name)
5. Whatistheuseofremove()function?
Ans.Youcanusetheremove()methodtodeletefilesbysupplyingthenameofthefiletobedeletedastheargument.
os.remove(file_name)
6. Whatistheuseofpicklemodule?
Ans.Picklemodulecanbeusedtostoreanykindofobjectinfileasitallowsustostorepythonobjectswiththeirstructure.Soforstoringdatainbinaryformat,wewillusepicklemodule.
7. Whatistheuseofdumpmethod?
Ans.pickle.dump()writestheobjectinfile,whichisopenedinbinaryaccessmode.
Syntaxofdump()methodis:
dump(object,fileobject)
8. Whatistheuseofloadmethod?
Ans.Forreadingdatafromfilewewillusepickle.load()toreadtheobjectfrompicklefile.
Syntaxofload()is:
object=load(fileobject)
9. Inhowmanywayscanendoffilebedetected?
Ans.
1. Whenendoffileisreached,readline()willreturnanemptystring.2. try:
whileTrue:
y=pickle.load(file)
—dosomething—
exceptEOFError:
pass
10.Whatisthedifferencebetweentextfilesandbinaryfiles?(or)Whataretheadvantagesofbinaryfiles?
Ans.Aswetalkoflinesintextfile,eachlineisterminatedbyaspecialcharacter,knownasEndofLine(EOL).Textfilesarestoredinhumanreadableformandtheycanalsobecreatedusinganytexteditor.
Abinaryfilecontainsarbitrarybinarydatai.e.numbersstoredinthefile,canbeusedfornumericaloperation(s).Sowhenweworkonbinaryfile,wehavetointerprettherawbitpattern(s)readfromthefileintocorrecttypeofdatainourprogram.Pythonprovidesspecialmodule(s)forencodinganddecodingofdataforbinaryfile.
11.WriteafunctionCountYouMe()inPythonwhichreadsthecontentsofatextfileNotes.txtandcountsthewordsYouandMe(notcasesensitive).
Ans.
defCountYouMe():
wordlist=[line.strip()forlineinopen(‘notes.txt’)]
#Searchingforawordinafile
count=0
forwordinwordlist:
words=word.split(”“)
forwordinwords:
#Removeallleadingandtrailingwhitespaces
word=word.strip().lower()
ifword==‘you’orword==‘me’:
count=count+1
ifcount==0:
print“notfoundinfile”
else:
print“count=”,count
CountYouMe()
Example:Ifthefilecontains
Youaremybestfriend
Youandmemakeagoodteam.
Outputwouldbe:count=3
12.Writeafunctiontocountthenumberoflinesstartingwithadigitinatextfile“Diary.txt”.
Ans.
defCountFirstDigit():
count=0
withopen(‘Diary.txt’,‘r’)asf:
whileTrue:
line=f.readline()
ifnotline:break
ifline[0].isdigit():
count=count+1
ifcount==0:
print“nolinestartswithadigit”
else:
print“count=”,count
CountFirstDigit()
13.GivenaclassTRAINasfollows,
classTRAIN:
def__init__(self):
self.trainno=0
self.trainname=”
self.start=”
self.dest=”
defget(self):
self.trainno=input(“Entertrainnumber”)
self.trainname=raw_input(“Entertrainname”)
self.start=raw_input(“Enterstartingplace”)
self.dest=raw_input(“Enterdestintion”)
defdisplay(self):
print“TrainNumber”,self.trainno
print“TrainName”,self.trainname
print“STARTINGPLACE”,self.start
print“DESTINATION”,self.dest
Writeafunctionto
(i)TowriteanobjectofTRAINtypeintoabinaryfile“TRAIN.dat”
(ii)Tosearchanddisplaydetailsoftrainsstartingfrom“MUMBAI”
(iii)Tosearchanddisplaydetailsoftrainswhosedestinationin“DELHI”
Ans.
frompickleimportload,dump
importos
importsys
fname=‘TRAIN.dat’
choice=0
whilechoice<5:
choice=input(“1-create2-display3-searchusingstart4-searchusingdest5-exit”)
ifchoice==1:
ofile=open(fname,‘wb’)
num=input(“Enternumberoftrains”)
foriinrange(num):
t=TRAIN()
t.get()
dump(t,ofile)
ofile.close()
elifchoice==2:
ifnotos.path.isfile(fname):
print“filedoesnotexist”
else:
ifile=open(fname,‘rb’)
try:
whileTrue:
t=load(ifile)
t.display()
exceptEOFError:
pass
ifile.close()
elifchoice==3:
ifile=open(fname,‘rb’)
start=raw_input(“Enterstartingstation”)
try:
whileTrue:
t=load(ifile)
ift.start==start:
t.display()
exceptEOFError:
pass
ifile.close()
elifchoice==4:
ifile=open(fname,‘rb’)
dest=raw_input(“Enterdestinationstation”)
try:
whileTrue:
t=load(ifile)
ift.dest==dest:
t.display()
exceptEOFError:
pass
ifile.close()
else:
break
PracticeQuestions
1.Writeafunctiontoreadthecontentofatextfile“DELHI.txt”anddisplayallthoselinesonscreen,whichareeitherstartingwith‘D’or‘M’.
2.Atextfile“PARA.txt”containsaparagraph.Writeafunctionthatsearchesforagivencharacterandreportstheno.ofoccurrencesofthecharacterinthefile.
3.Createadictionaryhavingdecimalequivalentofromannumerals.Storeitinabinaryfile.Writeafunctiontoconvertromannumbertodecimalequivalentusingthebinaryfiledata.
4.WriteafunctionCountHisHer()inPythonwhichreadsthecontentsofatextfile“Story.txt”andcountsthewordsHisandHer(notcasesensitive).
5.Writeafunctiontocountthenumberoflinesstartingwithuppercasecharactersinatextfile“Help.doc”.
6.Writeaprogramtoacceptafilenamefromtheuseranddisplayallthelinesfromthefilewhichcontainpythoncommentcharacter‘#’.
7. Write a program in Python to insert, delete, search and display details of allemployeesfromabinaryfile“Employee.dat”.
Chapter12:ExceptionHandling&Generators
Anexceptionisanevent,whichoccursduringtheexecutionofaprogram,thatdisruptsthenormalflowoftheprogram.Ingeneral,whenaPythonscriptencountersasituationthatitcan’tcopewith,itraisesanexception.AnexceptionisaPythonobjectthatrepresentsanerror.
Someunexpectedcondition(s)thatarenotpartofnormaloperationsplannedduringcodingare:
OutofMemoryInvalidfilenameAttemptingtowriteintoreadonlyfileGettinganincorrectinputfromuserDivisionbyzeroAccessinganoutofboundlistelementTryingtoreadbeyondendoffileSendingillegalargumentstoamethod
Ifanyofsuchsituationsisencountered,agoodprogramwilleitherhavethecodecheckforthemandperformsomesuitableactiontoremedythem,oratleaststopprocessinginawelldefinedwayaftergivingappropriatemessage(s).Sowhatwearesayingisifanerrorhappened,theremustbecodewritteninprogram,torecoverfromtheerror.Incaseifitisnotpossibletohandletheerrorthenitmustbereportedinuserfriendlywaytotheuser.
ExceptionhandlingExceptionshandlingistheprocessofrespondinginsuchsituations.Mostofthe
modernprogramminglanguagesprovidesupportwithhandlingexceptions.Theyofferadedicatedexceptionhandlingmechanism,whichsimplifiesthewayinwhichanexceptionsituationisreportedandhandled.
Forhandlingexceptionalsituationspythonprovides
1.raisestatementtoraiseexceptioninprogram
2.try…..exceptstatementforcatchingandhandlingtheerrors.
WhenaPythonscriptraisesanexception,itmusteitherhandletheexceptionimmediatelyotherwiseitwouldterminateandcomeout.Ifwehavesomesuspiciouscodethatmayraiseanexception,wecandefendourprogrambyplacingthesuspiciouscodeinatry:block.Afterthetry:block,includeanexcept:statement,followedbyablockofcodewhichhandlestheproblemaselegantlyaspossible.
Syntax:
try:
………………….
exceptExceptionA:
exceptExceptionB:
………………….
else:
Noexception
Asingletrystatementcanhavemultipleexceptstatements.Wecanalsoprovideagenericexceptclause,whichhandlesanyexception.Aftertheexceptclause(s),wecanincludeanelse-clause.Thecodeintheelse-blockexecutesifthecodeinthetry:blockdoesnotraiseanexception.
try:
n=input(“Enteryear”)
ifn<1000orn>2015:
raise“Invalidyear”,n
else:
month=input(“Entermonth”)
ifmonth<1ormonth>12:
raise“Invalidmonth”,month
else:
day=input(“Enterday”)
ifday<1orday>31:
raise“Invalidday”,day
else:
printday,‘/’,month,‘/’,n
except:
print“WrongValues”
Wecanalsousethesameexceptstatementtohandlemultipleexceptionsasfollows.
try:
………………….
except(Exception1[,Exception2[,…ExceptionN]]]):
………………….
else:
noexception
Thefinallyblockisaplacetoputanycodethatmustexecute,whetherthetry-blockraisedanexceptionornot.Thesyntaxofthetry-finallystatementis:
try:
………………….
finally:
………………….
Whenanexceptionisthrowninthetryblock,theexecutionimmediatelypassestothefinallyblock.Afterallthestatementsinthefinallyblockareexecuted,theexceptionisraisedagainandishandledintheexceptstatementsifpresentinthenexthigherlayerofthetry-exceptstatement.
Anexceptioncanhaveanargument,whichisavaluethatgivesadditionalinformationabouttheproblem.Thecontentsoftheargumentvarybyexception.
try:
………………….
exceptExceptionType,Argument:
…
Raise
Wecanraiseexceptionsinseveralwaysbyusingtheraisestatement.Thegeneralsyntaxfortheraisestatement.
raise[Exception[,args[,traceback]]]
Here,Exceptionisthetypeofexception(forexample,NameError)andargumentisavaluefortheexceptionargument.Theargumentisoptional;ifnotsupplied,theexceptionargumentisNone.
Thefinalargument,traceback,isalsooptional(andrarelyusedinpractice),andifpresent,isthetracebackobjectusedfortheexception.
User-DefinedExceptions
Pythonalsoallowsustocreateourownexceptionsbyderivingclassesfromthestandardbuilt-inexceptions.Forexample,let’stakeaclassthatissubclassedfromRuntimeError.Thisisusefulwhenyouneedtodisplaymorespecificinformationwhenanexceptioniscaught.
Araisestatementthatdoesnotincludeanexceptionnamewillsimplyraisethecurrent
exception.Hereexceptionnameisthetypeoferror,whichcanbestring,classorobjectandargumentisthevalue.AsargumentisoptionalitsdefaultvalueNoneisusedincasetheargumentisnotprovided.
S.No ErrorType Description
1 IOError I/Ooperationfails
2 EOFError Afilemethodtriestoreadbeyondthefile.
3 ZeroDivisionError Denominatorindivisioniszero.
4 NameError Variable/functionnameisnotfound
5 IndexError Index/Subscriptisoutofrange
6 ImportError Importstatementfailstofindthemoduledefinitionorfilename
7 IndentationError Incorrectindentation
8 TypeError Performanoperationonincorrecttypeofvalue
9 ValueError Built-infunctionreceivesanargumentofcorrecttypebutincorrectvalue
Table12.1:Typesofexceptions
Example:
>>>l=[11,22,33]
>>>i=input(“Enterindex”)
>>>ifi>len(l):
raiseIndexError
else:
printl[i]
Ifindexvalueis5,thecodewillraiseanerror,duringexecution.Theerrorwillbeindexerrorasmentionedinraisestatement.
>>>defmenu(choice):
ifchoice<1:
raise“invalidchoice”,choice
Inordertohandletheerrorsraisedbythestatement,wecanusetryexceptstatement.
try…..exceptisusedwhenwethinkthatthecodemightfail.Ifthishappensthenweareabletocatchitandhandlesameinproperfashion.Let’sre-considerthemenu()functiondefinedabovetohandletheerroralso:
whileTrue:
try:
x=int(raw_input(“Enteranumber”))
break
exceptValueError:
print”Thiswasnotavalidnumber.Enteravalidnumber”
Thiscodewillaskusertoinputavalueuntilavalidintegervalueisentered.
Oncewhileloopisenteredexecutionoftryclausebegins,ifnoerrorisencountered,i.e.thevalueenteredisinteger,exceptclausewillbeskippedandexecutionoftryfinishes.Ifanexceptionoccursi.e.anintegervalueisnotenteredthenrestoftryclauseisskippedandexceptcauseisexecuted.
Let’stakeanexampleofexceptionhandlingindatafile.
try:
f=open(“testfile”,“w”)
f.write(“Thisismytestfileforexceptionhandling!!”)
exceptIOError:
print“Error:can'tfindfileorreaddata”
else:
print“Writtensuccessfully”
Thiswillproducethefollowingresult,ifyouarenotallowedtowriteinthefile:
Error:can’tfindfileorreaddata
Generatorfunctions
Whenanormalpythonfunctioniscalled,inaprogram,thecontrolfromcallingfunctionisshiftedtocalledfunction.Executionofcalledfunctionstartsfromfirstlineandcontinuesuntilareturnstatementorexceptionorendoffunctionisencountered.Inallthesesituations,thecontrolisreturnedbacktocallerfunction.Thatmeansanyworkdonebythecalledfunctionforprovidingtheresultislost.Touseitagainwewillagaincallthefunctionanditsexecutionwillstartfromscratch.
Sometimesinprogrammingweneedtohavefunctionswhichareabletosaveitswork,sothatinsteadofstartingfromscratchthefunctionstartsworkingfromthepointwhereitwasleftlast.Inotherwords,afunctionshouldbeabletoyieldaseriesofvaluesinsteadofjustreturningasinglevalue.Herereturningavaluealsoimpliesreturningofcontrol.
SuchfunctionsareGeneratorfunctions.Thesefunctionscansendbackavalueandlaterresumeprocessingfromtheplace,wheretheyleftoff.Thisallowsthefunctiontoproduceaseriesofvalues-overtime,ratherthancomputingthemallatonceandreturningalistofvalues.
Generatorfunctionsarenotmuchdifferentfromnormalfunctions,theyalsousedeftodefineafunction.Theprimarydifferencebetweengeneratorandnormalfunctionisthatgeneratorwillyieldavalueinsteadofreturningavalue.
The yield suspends the function and sends a value back to the caller while retainsenoughstatetoenablethefunctionimmediatelyafterthelast yield run.Thisallowsthegeneratorfunctiontoproduceaseriesofvaluesovertimeratherthancomputingthemallatonceandsendingthembackinalist.
Let’sgeneratethecubesofnumbers.
Example12.1:Generatingcubeofnumbers
>>>defcube_generator(n):
foriinrange(n):
yieldi**3
it’s used in a for loop, control returns to the function afteritsyieldstatementeachtimethroughtheloop:
>>>foriincube_generator(5):
printi,#Python2.x
Output:
0:1:8:27:64:
Ifweusereturninsteadofyield,theresultis:
>>>defcube_generator(n):
foriinrange(n):
returni**3
Traceback(mostrecentcalllast):
File””,line1,in
foriincubic_generator(5):
TypeError:‘int’objectisnotiterable
The function yields a value and so returns to its caller each time through the loop.When it is resumed, its prior state is restored and control picks up again aftertheyieldstatement.When
Example12.2:Fibonacciseries
deffibonacci(max):
a,b=0,1#1
whilea<max:
yielda#2
a,b=b,a+b#3
Let’srunthroughthiscode.
1. It startswith0 and 1, goes up slowly at first, then more and morerapidly. To start the sequence, we need two variables: a starts at 0,andbstartsat1.
2. aisthecurrentnumberinthesequence,soyieldit.3. b is the next number in the sequence, so assign that to a, but also
calculatethenextvaluea+bandassignthattobforlateruse.Notethat thishappens inparallel; ifa is3andb is5, thena,b=b, a+bwillsetato5(thepreviousvalueofb)andbto8(thesumofthepreviousvaluesofaandb).
Wecanuse a generator like fibonacci() in a for loopdirectly.The forloop will automatically call the next() function to get values fromthefibonacci()generatorandassignthemtotheforloopindexvariable(n).Eachtimethroughtheforloop,ngetsanewvaluefromtheyieldstatementinfibonacci(),andallwehave todo isprint itout.Once fibonacci() runsoutofnumbers(abecomesbiggerthanmax,whichinthiscaseis500),thentheforloopexitsgracefully.
Generatorscanbebetterintermsofmemoryusageandtheperformance.Theyallowfunctionstoavoiddoingalltheworkupfront.Thisisespeciallyusefulwhentheresultinglistsarehugeorwhenitconsumesalotofcomputationtoproduceeachvalue.Generatordistributes the time required to produce the series of values among loop iterations.Generators can provide simpler alternatives to manually saving the state betweeniterationsinclassobjects.
SolvedExamples1. Whatisexceptionhandling?
Ans.Errorsareexceptional,unusualandunexpectedsituationsandtheyareneverpartofthenormalflowofaprogram.Ifanerrorhappened,theremustbecodewritteninprogram,torecoverfromtheerror.Incaseifitisnotpossibletohandletheerrorthenitmustbereportedinuserfriendlywaytotheuser.
2.Whendowegettypeerror?
Ans.Whenwedonotgiveanumberforindex,
try:
num=[‘Red’,‘Blue’,‘Green’]
printnum[‘Red’]
exceptTypeError:
print‘Enteronlynumberforindex’
3.Whataregeneratorfunctions?
Ans.Generatorfunctionscansendbackavalueandlaterresumeprocessingfromtheplace,wheretheyleftoff.Thisallowsthefunctiontoproduceaseriesofvalues-overtime,ratherthancomputingthemallatonceandreturningalistofvalues.
Generatorfunctionsarenotmuchdifferentfromnormalfunctions,theyalsousedeftodefineafunction.Theprimarydifferencebetweengeneratorandnormalfunctionisthatgeneratorwillyieldavalueinsteadofreturningavalue.
Itistheyieldstatementwhichallowsthegeneratorfunctiontosuspendtheprocessingandsendavalue,simultaneouslyretainingtheexistingstateofgeneratortoresumeprocessingovertime.
4.Writeacodesnippettogeneratesquaresusinggeneratorfunctions.
Ans.
#Squaresusinggenerator
defSquare(n):
foriinrange(n):
yieldi**2
forkinSquare(6):
printk,
5.Howisyielddifferentfromreturn?
Ans.Yieldisakeywordthatisusedlikereturn,exceptthefunctionwillreturnagenerator.
6.Whatistheuseofraisestatement?Mentionitssyntax.
Ans.Raisestatementallowstheprogrammertoforceaspecifiedexceptiontooccur.Onceanexceptionisraised,it’suptocallerfunctiontoeitherhandleitusingtry/exceptstatementorletitpropagatefurther.
Syntaxofraiseis:
raise[exceptionname[,argument]]
7. Findoutthesituation(s)inwhichfollowingcodemaycrash.
whileloop==1:
try:
a=input(‘Enteranumbertosubtractfrom>‘)
b=input(‘Enterthenumbertosubtract>‘)
exceptNameError:
print“\nYoucannotsubtractaletter”
continue
exceptSyntaxError:
print“\nPleaseenteranumberonly.”
continue
printa-b
try:
loop=input(‘Press1totryagain>‘)
except(NameError,SyntaxError):
loop=0
Ans.
Thecodemightnotcrashasallexceptionshavebeentakencareof.
8.WriteafunctioncalledoopsthatexplicitlyraisesaIndexErrorexceptionwhencalled.Thenwriteanotherfunctionthatcallsoopsinsideatry/exceptstatementtocatchtheerror.WhathappensifyouchangeoopstoraiseKeyErrorinsteadofIndexError?
Ans.
defoops():
l=[1,2,3]
i=5
ifi>len(l):
raiseIndexError
else:
printl[i]
defhandled():
try:
oops()
except(IndexError):
print“Youaretryingtoaccessthelistwithaninvalidindex”
handled()
Output:
Youaretryingtoaccessthelistwithaninvalidindex
WhenweraiseKeyError,anexceptionisthrownonthescreen.
9.Writeafunctiontofindaverageofalistofnumbers.Yourfunctionshouldbeabletohandleanemptylistandalsolistcontainingstring.
Ans.
l=[]
try:
n=input(“Enternumberofnumbers”)
foriinrange(n):
l.append(input(“Enternumber”))
sum=0
foriinrange(len(l)):
sum=sum+l[i]
avg=sum/len(l)
print“Average=”,avg
exceptNameError:
print“Enteronlynumber”
exceptTypeError:
print“WrongType”
PracticeQuestions
1.Findoutthesituation(s)inwhichfollowingcodemaycrash
whileloop==1:
try:
a=input(‘Enteranumbertosquare>‘)
exceptNameError:
print“\nYoucannotsquareacharacter”
continue
exceptSyntaxError:
print“\nPleaseenteranumberonly.”
continue
printa*a
try:
loop=input(‘Press1totryagain>‘)
except(NameError,SyntaxError):
loop=0
2.Whatisthepurposeofyieldstatement?
3.WhataretheapplicationsofGeneratorfunctions?
4.Writeafunctiontosearchalistofnumbers.Yourfunctionshouldbeabletohandleastringinput.
5.Writeaprogram,toacceptadateasday,month&yearfromuserandraiseappropriateerror(s),iflegalvalue(s)isnotsupplied.Displayappropriatemessagetilluserinputscorrectvalue(s).
6.Createaclassstudenttostorestudentdata.Ensurethatwhileacceptingthedataincorrectentryisproperlyhandled.
Chapter13:SampleApplications
Project1:Inventorymanagement
Createaclassitemtostoreinformationofdifferentitems,existinginashop.Atleastfollowingistobestoredw.r.t.eachitemcode,name,price,qty.Writeaprogramtoacceptthedatafromuserandstoreitpermanentlyinthefile.
Program:
importpickle
importos
importsys
classITEM:
def__init__(self):
self.itemcode=0
self.itemname=”
self.price=0.0
self.qty=0
defget(self):
self.itemcode=input(“Enteritemcode”)
self.itemname=raw_input(“Enteritemname”)
self.price=float(raw_input(“Enterprice”))
self.qty=input(“Enterquantity”)
pickle.dump(self,open(“save.txt”,“wb”))
print“SuccessfullySaved”
defdisplay(self):
print“Readingfromthefile”
self=pickle.load(open(“save.txt”,“rb”))
print“ItemCode”,self.itemcode
print“ItemName”,self.itemname
print“Price”,self.price
print“Quantity”,self.qty
x=ITEM()
x.get()
x.display()
Outputscreenshot:
Project2:Quiz
Thequizprojecthasanadministratorwhocancreateaquizandviewallquestions.Anyotheruserisgivenasetofsay20questionsonebyoneandtheirscoreiscalculatedforeachcorrectanswer.Attheendofthequiz,theirscoresaredisplayed.
#Quizclasscontainsthequestionsandthecorrectanswers
filename=“Quiz.txt”
ans={}
#Getinformationfromfiles
importos
ifos.path.exists(filename):
store=open(filename,‘r’)
forlineinstore:
term=line.rstrip()
answer=store.next().rstrip()
ans[term]=answer
store.close()
cont=0
ch=0
whilech==0:
choice=int(raw_input(“MENU1-CREATE2-PLAY3-QUIT”))
ifchoice==1:
whilecont==0:
term=raw_input(“Enterquestion:”)
term=term.rstrip()
whiletermnotinans:
answer=raw_input(“Enteranswer”)
ans[term]=answer
store=open(filename,‘w’)
forterm,answerinans.items():
store.write(str(term)+‘\n’)
store.write(answer+‘\n’)
store.close()
cont=int(raw_input(“Aretheremorequestions0tocontinue”))
elifchoice==2:
print“WelcometoQuiz”
score=0
forques,answerinans.items():
printstr(ques)
correct=ans.get(ques)
userans=raw_input(“Ans:”)
ifuserans==correct:
score=score+1
print“Youscored“,score,“outof”,len(ans)
else:
print“ThankYou”
break
ch=int(raw_input(“Doyouwishtocontinue..press0”))
Project3:Databasesoperationsusingpython
ProblemDescription
Writeasimplepythonprogramtoconnecttoadatabaseandperformdatabaseoperations.
Technicaldocumentation:
Gotohttps://code.google.com/p/pyodbc/downloads/list
Downloadtherequiredversion
Startbyimportingthepyodbcmodule
importpyodbc
Connections
TheConnectionobjectrepresentsasingleconnectiontothedatabaseandisobtainedfromthemodule’sconnectfunction:
cnxn=pyodbc.connect(‘DRIVER={SQLServer};SERVER=localhost;DATABASE=mine;UID=me;PWD=pwd’)
Therearetwoprimaryfeaturesoftheconnectionobject:
1. Youusecnxn.cursor()tocreateanewCursor.
2. Youusecnxn.commit()orcnxn.rollback()tocommitorrollbackworkperformedwiththeCursor.
commit
Weneedtoenableautocommit(inthepyodbc.connectfunctionorwithConnection.autocommit),alluncommitedworkwillbediscardedwhentheConnectionobjectisclosed.Wemustcallcnxn.commit()
cnxn=pyodbc.connect(…)#doworkhere…cnxn.commit()cnxn.close()
Cursors
CursorobjectsareusedtoexecuteSQL.
Program
importpyodbc
#ConnectionstringServername,databasename,userid=saandpassword
con=pyodbc.connect(‘DRIVER={SQLServer};SERVER=WIN-URCSEH98ZFA;DATABASE=record;UID=sa;PWD=password12%’)
#createacursorforthisconnection
cur=con.cursor()
whileTrue:
choice=input(“1-VIEW2-INSERT3-DELETE4-UPDATE5-SEARCH6-EXIT”)
ifchoice==1:
Select_Command=(“SELECT*fromstudent”)
cur.execute(Select_Command)
results=cur.fetchall()
print“RollNoNameGrade”
forrinresults:
print(str(r[0])+”“+r[1]+r[2])
elifchoice==2:
roll=input(“Entertherollnumbertobeinserted”)
sname=raw_input(“Enterthenametobeinserted”)
grade=raw_input(“Enterthegradetobeinserted”)
insert_command=(“insertintostudent(RollNo,Name,Grade)VALUES(?,?,?)”)
cur.execute(insert_command,roll,sname,grade)
con.commit()
elifchoice==3:
roll=input(“Entertherollnumbertobedeleted”)
delete_command=(“deletefromstudentwhererollno=?”)
try:
cur.execute(delete_command,roll)
con.commit()
except:
print(“Errorindelete”)
elifchoice==4:
roll=input(“Entertherollnumbertobeupdated”)
newgrade=raw_input(“Enterthenewgrade”)
update_command=(“updatestudentsetgrade=?whererollno=?”)
try:
cur.execute(update_command,newgrade,roll)
con.commit()
except:
print(“Errorinupdate”)
elifchoice==5:
roll=input(“Entertherollnumbertobesearched”)
search_command=(“SELECT*fromstudentwhererollno=?”)
cur.execute(Select_Command,roll)
results=cur.fetchone()
print(str(r[0])+”“+r[1]+r[2])
else:
print“Done”
break
con.close()
Outputscreenshot:
Project4:CALCULATOR
ThisprojectaimstocreateasimplecalculatorusingclassesandGUI.
SourceCode:
#calc.py-aPythoncalculator
fromTkinterimport*
importmath
#themainclass
classCalc():
def__init__(self):
self.total=0
self.current=””
self.new_num=True
self.op_pending=False
self.op=””
self.eq=False
defnum_press(self,num):
self.eq=False
temp=text_box.get()
temp2=str(num)
ifself.new_num:
self.current=temp2
self.new_num=False
else:
iftemp2==‘.’:
iftemp2intemp:
return
self.current=temp+temp2
self.display(self.current)
defcalc_total(self):
self.eq=True
self.current=float(self.current)
ifself.op_pending==True:
self.do_sum()
else:
self.total=float(text_box.get())
defdisplay(self,value):
text_box.delete(0,END)
text_box.insert(0,value)
defdo_sum(self):
ifself.op==“add”:
self.total+=self.current
ifself.op==“minus”:
self.total-=self.current
ifself.op==“times”:
self.total*=self.current
ifself.op==“divide”:
self.total/=self.current
ifself.op==‘square’:
self.total=math.pow(self.total,self.current)
self.new_num=True
self.op_pending=False
self.display(self.total)
defoperation(self,op):
self.current=float(self.current)
ifself.op_pending:
self.do_sum()
elifnotself.eq:
self.total=self.current
self.new_num=True
self.op_pending=True
self.op=op
self.eq=False
defcancel(self):
self.eq=False
self.current=“0”
self.display(0)
self.new_num=True
defall_cancel(self):
self.cancel()
self.total=0
defsign(self):
self.eq=False
self.current=-(float(text_box.get()))
self.display(self.current)
sum1=Calc()
root=Tk()
cal=Frame(root)
cal.grid()
root.title(“Calculator”)
text_box=Entry(cal,justify=RIGHT)
text_box.grid(row=0,column=0,columnspan=3,pady=5)
text_box.insert(0,“0”)
#makethebuttons
numbers=“123456789”
i=0
bttn=[]
forjinrange(1,4):
forkinrange(3):
bttn.append(Button(cal,text=numbers[i],bg=‘black’,fg=‘white’,font=‘bold’))
bttn[i].grid(row=j,column=k,pady=5)
bttn[i][“command”]=lambdax=numbers[i]:sum1.num_press(x)
i+=1
zero=Button(cal,text=‘0’,bg=‘black’,fg=‘white’,font=‘bold’)
zero[‘command’]=lambda:sum1.num_press(0)
zero.grid(row=4,column=1,pady=5)
multiply=Button(cal,text=‘X’,bg=‘green’,fg=‘black’,font=‘bold’)
multiply[‘command’]=lambda:sum1.operation(‘times’)
multiply.grid(row=2,column=3,pady=5)
minus=Button(cal,text=‘-‘,bg=‘green’,fg=‘black’,font=‘bold’)
minus[‘command’]=lambda:sum1.operation(‘minus’)
minus.grid(row=3,column=3,pady=5)
point=Button(cal,text=‘.’,bg=‘black’,fg=‘white’,font=‘bold’)
point[‘command’]=lambda:sum1.num_press(‘.’)
point.grid(row=4,column=0,pady=5)
add=Button(cal,text=‘+’,bg=‘green’,fg=‘black’,font=‘bold’)
add[‘command’]=lambda:sum1.operation(‘add’)
add.grid(row=4,column=3,pady=5)
neg=Button(cal,text=‘+/-‘,bg=‘blue’,fg=‘black’,font=‘bold’)
neg[‘command’]=sum1.sign
neg.grid(row=5,column=0,pady=5)
cancel=Button(cal,text=‘C’,bg=‘red’,fg=‘black’,font=‘bold’)
cancel[‘command’]=sum1.cancel
cancel.grid(row=5,column=1,pady=5)
clear_all=Button(cal,text=‘AC’,bg=‘red’,fg=‘black’,bd=10)
clear_all[‘command’]=sum1.all_cancel
clear_all.grid(row=1,column=3,pady=5)
equals=Button(cal,text=‘=’,bg=‘orange’,fg=‘black’,font=‘bold’)
equals[‘command’]=sum1.calc_total
equals.grid(row=4,column=2,pady=5)
divide=Button(cal,text=‘/’,bg=‘green’,fg=‘black’,font=‘bold’)
divide[‘command’]=lambda:sum1.operation(‘divide’)
divide.grid(row=5,column=3,pady=5)
square=Button(cal,text=‘^’,bg=‘blue’,fg=‘white’,font=‘bold’)
square[‘command’]=lambda:sum1.operation(‘square’)
square.grid(row=5,column=2,pady=5)
root.mainloop()
SourceCode:Calculatorproject
Fig:Calculatorprojectscreenshots
Solutionstopracticequestions(selected)
Chapter2
1.name1=raw_input(“Firstperson-enteryourname”)
name2=raw_input(“Secondperson-enteryourname”)
print“Hello”,name1
print“Hello”,name2
3.a)45
b)7.0
Chapter31. defSubtractNumber(x,y):
result=x-y
returnresult
#Get2numbers
num1=input(“Enterfirstnumber”)
num2=input(“Entersecondnumber”)
res=SubtractNumber(num1,num2)
print“Subtractionresult”,num1,”-“,num2,”=”,res
2.defpower(x,y=2):
sum=1
foriinrange(1,y+1):
sum=sum*x
returnsum
print“Usingdefaultargument”
num=input(“Enterthebase”)
printpower(num)
print“Valueprovidedforbotharguments”
exp=input(“Enterexponent”)
printpower(num,exp)
Chapter4
1.
importmath
importcmath
print“\nEnterthevaluesfora,bandc.”
a=float(raw_input(“a?”))
b=float(raw_input(“b?”))
c=float(raw_input(“c?”))
ifb*b-4*a*c<0:
print“Thisquadratichasimaginaryroots.”
root=(-b-cmath.sqrt(b*b-4*a*c))/(2*a)
print“x=”,root
root=(-b+cmath.sqrt(b*b-4*a*c))/(2*a)
print“x=”,root
elifb*b-4*a*c==0:
print“Thisquadraticequationhasequalroots.”
root=-b/(2*a)
print“x=”,root
else:
print“Thisquadratichasrealanddistinctroots.”
root=(-b-math.sqrt(b*b-4*a*c))/(2*a)
print“x=”,root
root=(-b+math.sqrt(b*b-4*a*c))/(2*a)
print“x=”,root
raw_input()
2.
importmath
print“\nEntercustomer’sname”
name=raw_input(“name?”)
print“\nEnterthepreviousmonth’sreading.”
prev=float(raw_input(“prev?”))
print“\nEnterthecurrentmonth’sreading.”
curr=float(raw_input(“curr?”))
units=curr-prev
ifunits<=100:
bill=units*4.00;
elifunits>100andunits<500:
bill=400+(units-100)*5.00;
else:
bill=400+2000+(units-500)*6.00;
print“No.ofunitsconsumed=“,units
print“Amountpayabletotheelectricitydepartment=Rs”,bill
raw_input()
3.
importmath
sum=0
sign=1
x=0
n=int(raw_input(“Enterthevalueofn:”))
x=int(raw_input(“Enterthevalueofx:”))
j=1
i=1
whilei<n:
f=1
whilej<i:
f=f*j
j=j+1
sum=sum+sign*(pow(x,i)/f)
sign=-sign;
i=i+1
print”1-x/1!+x^2/2!-x^3/3!+…+(-1)^nx^n/n!=”,sum
raw_input()
Chapter5
1.#Countingvowels
count=0;
line=raw_input(“Enteraword:”)
i=0
foriinrange(0,len(line)):
line=line.lower()
if((line[i]==‘a’)or(line[i]==‘e’)or(line[i]==‘i’)or(line[i]==‘o’)or(line[i]==‘u’)):
count=count+1
print“\nNoofvowels=“,count
raw_input()
2.
importre
value=[]
print””””Rules:Atleast1uppercaseletter,1lowercaseletter,
1specialcharacterand1numbermin6charactermax20characters””””
items=[xforxinraw_input(“Enterthepasswordlist”).split(‘,’)]
forpinitems:
p=p.strip()
iflen(p)<6orlen(p)>20:
print“Lengtherror”,p
continue
ifnotre.search(“[a-z]”,p):
continue
elifnotre.search(“[0-9]”,p):
continue
elifnotre.search(“[A-Z]”,p):
continue
elifnotre.search(“[?$#@!*]”,p):
continue
elifre.search(“\s”,p):
continue
else:
pass
value.append(p)
print“Thevalidpasswordlistis”
print“,”.join(value)
4.
#Getnamesfromtheuser
names=list()
n=int(raw_input(“Enterthenumberofnames:-”))
print“Enterthenames”;
foriinrange(0,n):
names.append(raw_input())
foriinrange(0,n):
forjinrange(i,n):
ifnames[i]>names[j]:
temp=names[i]
names[i]=names[j]
names[j]=temp
print“SortedArray:\n”
foriinrange(n):
printnames[i]
raw_input()
Chapter61.defsumodd(L):
pos=0
sum=0
whilepos<len(L):
ifL[pos]%2==1:
sum=sum+L[pos]
pos=pos+1
printsum
2. importrandom
print”TocreateamatrixoftheformM*M”
m=input(“Enterthenumberofrows:-“)
n=input(“Enterthenumberofcolumns:-“)
a=[[random.randint(1,9)forrowinrange(n)]forcolinrange(m)]
foriinrange(m):
forjinrange(n):
printa[i][j],
print”__________ToPrintTheRowSum______________”
foriinrange(m):
sum=0
forjinrange(n):
sum=sum+a[i][j]
printsum,
print”___________ToPrintTheColumnSum____________”
foriinrange(n):
sum=0
forjinrange(m):
sum=sum+a[j][i]
printsum
print”_______________LEFTDIAGONALSUM______________”
sum=0
foriinrange(m):
forjinrange(n):
ifi==j:
sum=sum+a[i][i]
printsum
print”_____________RIGHTDIAGONALSUM______________”
sum=0
foriinrange(m):
forjinrange(n):
ifi+j==m-1:
sum=sum+a[i][j]
printsum,
3.defoverlapping(a,b):
l1=len(a)
l2=len(b)
foriinrange(l1):
forjinrange(l2):
ifa[i]==b[j]:returnTrue
else:returnFalse
6.defduplicates():
a=[1,2,3,2,1,5,6,5,5,5]
d={}
forelemina:
ifelemind:d[elem]+=1else:d[elem]=1
printelem
print[xforx,yind.items()ify>1],print“haveduplicates”
printd
Chapter7
1.city=dict()
n=5
i=l
whilei<=n:
a=raw_input(“entercityname”)
b=raw_input(“enterpopulation”)
city[a]=b
i=i+l
printcity
2.defprint_menu():
print(‘1.AddaPhoneNumber’)
print(‘2.RemoveaPhoneNumber’)
print(‘3.SearchaPhoneNumber’)
print(‘4.ModifyaPhoneNumber’)
print(‘5.Displaythephonebook’)
print(‘6.Quit’)
phonebook={}
menu_choice=0
print_menu()
whilemenu_choice!=6:
menu_choice=int(raw_input(”Enterchoice(1-5):“))
ifmenu_choice==1:
print(“Insertion”)
name=raw_input(“Name:“)
phone=raw_input(“Number:“)
phonebook[name]=phone
elifmenu_choice==2:
print(”Deletion”)
name=raw_input(“Name:“)
ifnameinphonebook:
delphonebook[name]
else:
print(name,“wasnotfound”)
elifmenu_choice==3:
print(“Searching”)
name=raw_input(“Name:“)
ifnameinphonebook:
print(“Thenumberis”,phonebook[name])
else:
print(name,“wasnotfound”)
elifmenu_choice==4:
print(“Update”)
name=raw_input(“Name:“)
ifnameinphonebook:
newno=raw_input(“Enternewtelephonenumber”)
phonebook[name]=newno
else:
print(name,“wasnotfound”)
elifmenu_choice==5:
print(“Phonebook:”)
forxinphonebook.keys():
print(x,phonebook[x])
else:
print“Thankyou”
3.
customer=dict()
n=input(”Entertotalnumberofcustomers”)
i=1
whilei<=n:
a=raw_input(“entercustomername”)
b=raw_input(“entercustomernumber”)
customer[a]=b
i=i+1
name=raw_input(“entercustomernametodelete”)
delcustomer[name]
l=customer.keys()
print“CustomerInformation”
print“Name”,‘\t’,“number”
foriinl:
printi,‘\t’,customer[i]
Chapter81. t=tuple()
n=input(“Entertotalnumberofemployees”)
foriinrange(n):
a=input(“entersalaryofemployee:”)
t=t+(a,)
print“maximumsalary=”,max(t)
print“minimumsalary=”,min(t)
Chapter10
1.
classitems:
def__init__(self,s=None):
ifs==None:
self.itemname=”
self.itemcode=0
self.itemprice=0.0
self.itemqty=0
else:
self.itemname=s.itemname
self.itemcode=s.itemcode
self.itemprice=s.itemprice
self.itemqty=s.itemqty
defget(self):
print”
self.itemname=raw_input(‘Enternameofitem:‘)
self.itemcode=input(‘Enteritemcode:‘)
self.itemprice=float(raw_input(‘Enteritemprice:‘))
self.itemqty=input(‘Enterquantity:‘)
print”
defshow(self):
printself.itemname,‘\t\t’,self.itemcode,‘\t\t’,self.itemprice,‘\t\t’,self.itemqty
s=items()
inventorylist=[]
n=input(‘Enternumberofitems:‘)
foriinrange(n):
s.get()
inventorylist.append(items(s))
print“ITEMSSORTEDBYPRICE”
foriinrange(len(inventorylist)):
forjinrange(i+1,len(inventorylist)):
ifinventorylist[i].itemprice>inventorylist[j].itemprice:
inventorylist[i],inventorylist[j]=inventorylist[j],inventorylist[i]
print‘ITEM\t\tCODE\t\tPRICE\t\tQUANTIY’
foritemininventorylist:
item.show()
raw_input()
2.
definsertionsort(a):
foriinrange(1,len(a)):
currentval=a[i]
pos=i
whilepos>0anda[pos-1]>currentval:
a[pos]=a[pos-1]
pos=pos-1
a[pos]=currentval
print“Yoursortedlistis”,a
a=[]
n=input(“Enternumberofintegers:-”)
foriinrange(n):
a.append(input(“Enternumbers:-”))
print“Yourlistis”,a
insertionsort(a)
6.classstack:
s=[]
defpush(self):
a=input(“Enternumber:”)
stack.s.append(a)
defpop(self):
if(a.s==[]):
print“StackEmpty”
else:
print“Deletedelementis:“,a.s.pop()
defdisplay(self):
l=len(stack.s)
print“STACKCONTENTS”
foriinrange(l-1,-1,-1):
printstack.s[i]
a=stack()
n=input(“Entercountofnumbers”)
foriinrange(n):
a.push()
a.pop()
a.display()
7.#Bookstack
classstack:
s=[]
count=0
defpush(self):
no=input(“Enterbooknumber”)
name=raw_input(“Enteranyname:”)
stack.book=name
stack.s.append(stack.book)
stack.count=stack.count+1
defpop(self):
stack.count=stack.count-1
printstack.s.pop()
printstack.count
#print“Deletedelementis:“,stack.s[stack.count].pop()
defdisplay(self):
l=len(stack.s)
print“STACKCONTENTS”
print“BOOKNUM”,““,“BOOKNAME”
foriinrange(l-1,-1,-1):
printi+1,““,stack.s[i]
a=stack()
choice=0
whilechoice<4:
choice=int(raw_input(“Enter1-push2-pop3-view4-quit”))
ifchoice==1:
n=input(“Enterno.ofnames”)
foriinrange(n):
a.push()
elifchoice==2:
a.pop()
elifchoice==3:
a.display()
else:
break
8.classReservationQ:
def__init__(self):
self.items=[]
defisEmpty(self):
returnself.items==[]
defenqueue(self,item):
self.items.insert(0,item)
defdequeue(self):
returnself.items.pop()
defsize(self):
returnlen(self.items)
defdisplay(self):
print“FRONT—>”,
x=self.size()
forainrange(x-1,-1,-1):
printself.items[a],“—>”,
print“REAR”
choice=0
x=ReservationQ()
whilechoice<4:
choice=input(“Enter1-insert2-delete3-view4-quit”)
ifchoice==1:
ifx.size()>4:
print”Reservationisnotpossible”
break
item=raw_input(“EnterPNRnumber”)
x.enqueue(item)
elifchoice==2:
ifx.isEmpty():
print“ReservationQueueisempty”
break
x.dequeue()
elifchoice==3:
x.display()
else:
break
Chapter11
1.defCountDorM():
count=0
withopen(‘DELHI.txt’,‘r’)asf:
whileTrue:
line=f.readline()
ifnotline:break
ifline[0]==‘D’orline[0]==‘M’:
count=count+1
ifcount==0:
print“nolinestartswithDorM”
else:
print“count=”,count
CountDorM()
2.defcountchar():
fname=“story.txt”
count=0
c=raw_input(“Enterthecharactertosearchfor”)
withopen(fname,‘r’)asf:
forlineinf:
forwordinline:
forcharinword:
ifchar.strip()==c.strip():
count=count+1
print“No.ofoccurencesof”,c,“=”,count
countchar()
3.Ans.
importpickle
#Creatingthedictionary
R={‘I’:1,‘II’:2,‘III’:3,‘IV’:4,‘V’:5}
file=open(‘myfile.dat’,‘wb’)
pickle.dump(R,file)
file.close()
roman=raw_input(“Entertheromannumeral”)
#readpythondictbackfromthefile
ifile=open(‘myfile.dat’,‘rb’)
R=pickle.load(ifile)#readingdatafrombinaryfile
try:
print“DecimalEquivalentof”,roman,“is”,R[roman]
except:
print“Noequivalentfound”
6.
Ans.
try:
forlineinopen(“story.txt”):
line=line.strip()
ifline[0]==‘#’:
printline
except:
print‘FileNotFound’
Chapter12
5.
try:
n=input(“Enteryear”)
ifn<1000orn>2015:
raise“Invalidyear”,n
else:
month=input(“Entermonth”)
ifmonth<1ormonth>12:
raise“Invalidmonth”,month
else:
day=input(“Enterday”)
ifday<1orday>31:
raise“Invalidday”,day
else:
printday,‘/’,month,‘/’,n
except:
print“WrongValues”
6.classStudent:
#constructortocreateanobject
def__init__(self):
self.rollno=0
self.name=”
self.marks=[0,0,0]
self.grade=”
defread(self):
#Thisfunctiongetsthedetailsofastudentfromtheuser
x=1
whilex==1:
try:
self.rollno=input(“Enterrollnumber:-”)
exceptNameError:
print“Rollnumbershouldbeanumber”
continue
self.name=raw_input(“Entername:-”)
try:
self.marks=float(raw_input(“Enterthemarks-”))
exceptNameError:
print“Marksshouldbedecimal”
continue
exceptValueError:
print“Marksshouldbedecimal”
continue
x=0
s=Student()
s.read()
Referencebooks1.“PythonProgrammingfortheAbsoluteBeginner”byMichaelDawsonPremierPress2003.2.PythonTutorialRelease2.6.3byGuidovanRossumandFredL.Drake,Jr.,editorOctober06,2009-PythonSoftwareFoundation3.“ComputerScience–ClassXI”byCentralBoardofSecondaryEducation,NewDelhi2013.4.“IntroductiontoProgrammingUsingPython”byBrianHeinold,DepartmentofMathematicsandComputerScience,MountSt.Mary’sUniversity5.“COMPREHENSIVECOMPUTERSCIENCEWITHPYTHON–XI”byPavithraKarthik,LaxmiPublications,20156.“COMPREHENSIVECOMPUTERSCIENCEWITHPYTHON–XII”byPavithraKarthik,LaxmiPublications,2016
Weblinks1. http://www.tutorialspoint.com/python2. http://docs.python.org/3. http://www.pythontutor.com/4. www.studiestoday.com
Otherbooksbythesameauthor1. “APracticalWorkbookforCBSEComputerScience(C++)–ClassXI”byPavithra
Karthik,LaxmiPublications2. “APracticalWorkbookforCBSEComputerScience(C++)–ClassXII”byPavithra
Karthik,LaxmiPublications3. “APracticalWorkbookforCBSEComputerScience(Python)–ClassXI”byPavithra
Karthik,LaxmiPublications4. “APracticalWorkbookforCBSEComputerScience(Python)–ClassXII”byPavithra
Karthik,LaxmiPublications5. “COMPREHENSIVECOMPUTERSCIENCEWITHPYTHON–XI”byPavithra
Karthik,LaxmiPublications,20156. “COMPREHENSIVECOMPUTERSCIENCEWITHPYTHON–XII”byPavithra
Karthik,LaxmiPublications,20167. “COMPREHENSIVECOMPUTERSCIENCEWITHC++–XI”byPavithraKarthik,
LaxmiPublications,20168. “COMPREHENSIVECOMPUTERSCIENCEWITHC++–XII”byPavithraKarthik,
LaxmiPublications,2016