Python Programming Made Easy: For Beginners Grade 11 & 12 ...
Transcript of Python Programming Made Easy: For Beginners Grade 11 & 12 ...
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