Transcript
12Tamil Nadu
SAMPLE PAPERS
SCIENCE STREAM*jĜ *English *Physics *Chemistry
*Mathematics *Biology *Computer Science
FULL MARKS PVT LTD(Progressive Educational Publishers)
CHENNAI - 600 017
Key BooK
for
Published by:
# 10/34, Mahalakshmi Street, T. Nagar, Chennai-600017Phone: 044- 24333508; +91 9962012902Website: www.fullmarks.orgE-mail: chennai@fmpl.in
© Publishers
All rights reserved. No part of this publication may be reproduced or transmitted, in any form or by any means, without permission. Any person who does any unauthorised act in relation to this publication may be liable to criminal prosecution and civil claims for damages.
Branches:• Ahmedabad • Bengaluru • Bhopal • Chennai • Dehradun • Guwahati • Hyderabad • Jaipur • Kochi • Kolkata • Lucknow • Mumbai • Patna • Ranchi
FIRST EDITION
“This book is meant for educational and learning purposes. The author(s) of the book has/have taken all reasonable care to ensure that the contents of the book do not violate any existing copyright or other intellectual property rights of any person in any manner whatsoever. In the event the author(s) has/have been unable to track any source and if any copyright has been inadvertently infringed, please notify the publisher in writing for corrective action.”
Sample Paper-4PART - III
25. •Constructorsarefunctionsthatbuildtheabstractdatatype. • Selectorsarefunctionsthatretrieveinformationfromthedatatype. 26. A search algorithm is the step-by-step procedure used to locate specific data among a
collectionofdata.Typesofsearchingalgorithmsare*Linearsearch*Binarysearch*Hashsearch*BinaryTreesearch
27. Python uses the symbols and symbol combinations as delimiters in expressions, lists,dictionariesandstrings.Followingarethedelimiters.
( ) [ ] { }
, : . ‘ = ;
+= -= *= /= //= %=
&= |= ^= >>= <<= **=
28. Aloopplacedwithinanotherloopiscalledasnestedloopstructure.Onecanplaceawhilewithinanotherwhile;forwithinanotherfor;forwithinwhileandwhilewithinfortoconstructsuchnestedloops.
Followingisanexampletoillustratetheuseofforlooptoprintthefollowingpattern 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
29. n=input("Enteranynumber") sum=0 foriinrange(i,n+1): sum=sum+i print"sum=",sum Output: Enteranynumber5 sum=15
Three-mark & Five-mark Answers for Unsolved Sample Papers
COMPUTER SCIENCE
G-1
G-2 Computer SCienCe – XII
30. sort()functionsortstheelementinlist. Syntax: List.sort(reverse=True/False,Key=myFunc) Bothargumentsareoptional •IfreverseissetasTrue,listsortingisindescendingorder. •Ascendingisdefault. •Key=myFunc;"myFunc"-thenameoftheuserdefinedfunctionthatspecifiesthesorting criteria.
Example MyList=['Thilothamma','Tharani','Anitha','SaiSree','Lavanya'] MyList.sort() print(MyList)
Output: ['Anitha','Lavanya','SaiSree','Tharani','Thilothamma'] 31. SQLcommandwhichcomeunderTransferControlLanguageare: • CommitSavesanytransactionintothedatabasepermanently. • Roll backRestoresthedatabasetolastcommitstate. • Save pointTemporarilysaveatransactionsothatyoucanrollback. 32.
S.No. PYTHON C++
1. Pythonistypicallyan"interpreted"language C++istypicallya"compiled"language
2. Pythonisadynamic-typedlanguage C++iscompiledstaticallytypedlanguage
3. Datatypeisnotrequiredwhiledeclaringvariable
Datatypeisrequiredwhiledeclaringvariable
4. Itcanactbothasscriptingandgeneralpurposelanguage Itisageneralpurposelanguage
33. Pseudo code: 1. Startwiththefirstelement i.e., index=0,comparethecurrentelementwiththenext
elementofthearray. 2. Ifthecurrentelementisgreaterthanthenextelementofthearray,swapthem. 3. Ifthecurrentelementislessthanthenextorrightsideoftheelement,movetothenext
element.GotoStep1andrepeatuntilendoftheindexisreached.
PART - IV 34(a). Rules to be followed to format data in a CSV file
1. Eachrecord(rowofdata)istobelocatedonaseparateline,delimitedbyalinebreakbypressingenterkey.
ANSWERS G-3
Forexample: xxx,yyy denotesenterKeytobepressed
2. Thelastrecordinthefilemayormaynothaveanendinglinebreak. Forexample: ppp,qqq yyy,xxx
3. Theremaybeanoptionalheaderlineappearingasthefirstlineofthefilewiththesameformat as normal record lines.The headerwill contain names corresponding to thefieldsinthefileandshouldcontainthesamenumberoffieldsastherecordsintherestofthefile.
Forexample:field_name1,field_name2,field_name3 aaa,bbb,ccc zzz,yyy,xxxCRLF( Carriage Return and Line Feed) 4. Within the header and each record, there may be one or more fields, separated by
commas.Spacesareconsideredpartofafieldandshouldnotbeignored.Thelastfieldintherecordmustnotbefollowedbyacomma.Forexample:Red,Blue
5. Eachfieldmayormaynotbeenclosedindoublequotes.Iffieldsarenotenclosedwithdoublequotes,thendoublequotesmaynotappearinsidethefields.
Forexample:
"Red","Blue","Green" #Fielddatawithdoublequotes Black,White,Yellow #Fielddatawithoutdoublequotes
6. Fieldscontaininglinebreaks(CRLF),doublequotes,andcommasshouldbeenclosedindouble-quotes.Forexample:
Red,",",BlueCRLF#commaitselfisafieldvalue.Soitisenclosedwithdoublequotes Red,Blue,Green
7. Ifdouble-quotesareusedtoenclosefields,thenadouble-quoteappearinginsideafieldmustbeprecededwithanotherdoublequote.Forexample:
"Red,""Blue","Green",#sincedoublequotesisafieldvalueitisenclosedwith anotherdoublequotes,,White
[OR] (b) importtextwrap text= '"Stringsareimmutable.Sliceisa substringofamainstring.Strideisathirdargumentinslicingoperation"' text_without_Indentation=textwrap.dedent(text) wrapped=textwrap.fill(text_without_Indentation,width=50) print(textwrap.indent(wrapped,'*') print()
G-4 Computer SCienCe – XII
Output: • Stringsareimmutable.Sliceisa • substringofamainstring.Stride • isathirdargumentinslicingoperation 35(a) The range( ) is a function used to generate a series of values in Python.Using range( )
function,youcancreatelistwithseriesofvalues.Therange()functionhasthreearguments. Syntax of range ( ) function: range(startvalue,endvalue,stepvalue) where, • startvalue–beginningvalueofseries.Zeroisthedefaultbeginningvalue. • endvalue–upperlimitofseries.Pythontakestheendingvalueasupperlimit–1. • stepvalue– It is anoptional argument,which isused togeneratedifferent intervalof
values. Example : Generatingwholenumbersupto10 forxinrange(1,11): print(x) Output 1 2 3 4 5 6 7 8 9 10
[OR]
(b) (i) Todisplaythedetailsofallemployeesindescendingorderofpay.(ii)Todisplayallemployeeswhoseallowanceisbetween5000and7000.(iii)Toremovetheemployeeswhoaremechanic.(iv)Toaddanewrow.(v) Todisplaythedetailsofallemployeeswhoareoperators.Output:(i) SELECT*FROMemployeeORDERBYDESC;(ii) SELECT*FROMemployeeWHERE((allowance>=5000)AND(allowance<=7000));(iii) DELETEFROMemployeeWHEREdesig="Mechanic";(iv) INSERT INTO employee(Empcode,Name,desig,pay,allowance)VALUES('M1006','RAM','Mechanic',22000,8000);(v) SELECT*FROMemployeeWHEREdesig='operator';
ANSWERS G-5
36(a) Aswelearntinmathematics,thepythonisalsosupportsthesetoperationssuchasUnion,Intersection,differenceandSymmetricdifference.
(i) Union:Itincludesallelementsfromtwoormoresets Inpython,theoperator|isusedtounionoftwosets.Thefunctionunion()isalsousedtojoin
twosetsinpython. Example:ProgramtoJoin(Union)twosetsusingunionoperator set_A={2,4,6,8} set_B={'A','B','C','D'} U_set=set_A|set_B print(U_set) Output: {2,4,6,8,'A','D','C','B'}
(ii) Intersection:Itincludesthecommonelementsintwosets Theoperator&isusedtointersecttwosetsinpython.Thefunctionintersection()isalso
usedtointersecttwosetsinpython. Example:Programtoinsecttwosetsusingintersectionoperator set_A={'A',2,4,'D'} set_B={'A','B','C','D'} print(set_A&set_B) Output: {'A','D'}
(iii) Difference:Itincludesallelementsthatareinfirstset(saysetA)butnotinthesecondset(saysetB)
Theminus(–)operatorisusedtodifferencesetoperationinpython. Thefunctiondifference()isalsousedtodifferenceoperation. Example:Programtodifferenceoftwosetsusingminusoperator set_A={'A',2,4,'D'} set_B={'A','B','C','D'} print(set_A-set_B) Output: {2,4}
(iv) Symmetric difference:Itincludesalltheelementsthatareintwosets (saysetsAandB)butnottheonethatarecommontotwosets.
Thecaret(^)operatorisusedtosymmetricdifferencesetoperationinpython.Thefunctionsymmetric_difference()isalsousedtodothesameoperation.
Example: Program to symmetric difference of two sets usingcaretoperator
set_A={'A',2,4,'D'} set_B={'A','B','C','D'} print(set_A^set_B)
Set A Set B
Set A Set B
Set A Set B
Set A Set B
G-6 Computer SCienCe – XII
Output: {2,4,'B','C'}
[OR] (b) defrem_vowels(s): temp_str=" foriins: ifiin"aAeEiIoOuU": pass else: temp_str+=i print("Thestringwithoutvowels:",temp_str) str1=input("EnteraString:") rem_vowels(str1) Output: EnteraString:MathematicalfoundationsofComputerScience Thestringwithoutvowels:MthmtclfndtnsfCmptrScnc 37(a) Thefetchall()methodisusedtofetchallrowsfromthedatabasetable importsqlite3 connection=sqlite3.connect("Academy.db") cursor=connection.cursor() cursor.execute("SELECT*FROMstudent") print("fetchall:") result=cursor.fetchall() forrinresult: print(r) Output: fetchall: (1,'Akshay','B','M',87.8,'2001-12-12') (2,'Aravind','A','M',92.5,'2000-08-17') (3,'BASKAR','C','M',75.2,'1998-05-17') (4,'SAJINI','A','F',95.6,'2002-11-01') (5,'VARUN','B','M,80.6,'2001-03-14') (6,'PRIYA','A','F',98.6,'2002-01-01') (7,'TARUN','D','M',62.3,'1999-02-01')
[OR] (b) #include<iostream> usingnamespacestd; //Functiondeclaration intcube(intnum); intmain()
ANSWERS G-7
{ intnum; intc; cout<<"Enteranynumber:"<<endl; cin>>num; c=cube(num); cout<<"Cubeof"<<num<<"is"<<c; return0; } //Functiontofindcubeofanynumber intcube(intnum) { return(num*num*num); } //Savethisfileascube_file.cpp #NowselectFile→NewinNotepadandtypethePythonprogram #SavetheFileasfun.py #Programthatcompilesandexecutesa.cppfile #Pythonfun.py-ic:\pyprg\cube_file.cpp importsys,os,getopt defmain(argv): cpp_file=" exe_file=" opts,args=getopt.getopt(argv,"i:",['ifile=']) foro,ainopts: ifoin("-i","--ifile"): cpp_file=a+'.cpp' exe_file=a+'.exe' run(cpp_file,exe_file) defrun(cpp_file,exe_file): print("Compiling"+cpp_file) os.system('g++'+cpp_file+'-o'+exe_file) print("Running"+exe_file) print("-------------------") print os.system(exe_file) print if__name__=='__main__': main(sys.argv[1:])
G-8 Computer SCienCe – XII
Output of the above program Compilingc:\pyprg\cube_file.cpp Runningc:\pyprg\cube_file.exe ------------------- Enteranynumber: 5 Cubeof5is125 38(a) Pythonenablesreverseornegativeindexingforthelistelements.Thus,pythonlistsindexin
oppositeorder.Thepythonsets-1astheindexvalueforthelastelementinlistand-2fortheprecedingelementandsoon.ThisiscalledasReverseIndexing.
Example: Marks=[10,23,41,75] i=–1 whilei>=–4: print(Marks[i]) i=i+–1 Output 75 41 23 10
[OR]
(b) Sorts the element in list Bothargumentsareoptional • IfreverseissetasTrue,listsortingisindescendingorder. • Ascendingisdefault. • Key=myFunc;"myFunc"-thenameoftheuserdefinedfunctionthatspecifiesthesorting
criteria. MyList=['Thilothamma','Tharani','Anitha', 'SaiSree','Lavanya'] MyList.sort() print(MyList) MyList.sort(reverse=True) print(MyList) Output: ['Anitha','Lavanya','SaiSree','Tharani','Thilothamma'] ['Thilothamma','Tharani','SaiSree','Lavanya','Anitha']
ANSWERS G-9
Sample Paper-5PART - III
25. 1. Input - Zeroormorequantitiestobesupplied.2. Output - Atleastonequantityisproduced.3. Finiteness - Algorithmsmustterminateafterfinitenumberofsteps.4. Definiteness - All operations should be well defined. For example operations
involvingdivisionbyzeroortakingsquarerootfornegativenumberareunacceptable.
5. Effectiveness - Everyinstructionmustbecarriedouteffectively.6. Correctness - Thealgorithmsshouldbeerrorfree.7. Simplicity - Easytoimplement.8. Unambiguous - Algorithmshouldbeclearandunambiguous.Eachofitsstepsandtheir
inputs/outputsshouldbeclearandmustleadtoonlyonemeaning.9. Feasibility - Shouldbefeasiblewiththeavailableresources.10. Portable - An algorithm should be generic, independent of any programming
languageoranoperatingsystemabletohandleallrangeofinputs.11. Independent - An algorithm should have step-by-step directions,which should be
independentofanyprogrammingcode. 26. CSV File cannot store charts or graphs. It stores data but does not contain formatting,
formulas,macros,etc. ACSVfile isalsoknownasaFlatFile.Files in theCSVformatcanbeimportedtoand
exportedfromprogramsthatstoredataintables,suchasMicrosoftExcelorOpenOfficeCalc. 27. SAVEPOINT command
TheSAVEPOINTcommandisusedtotemporarilysaveatransactionsothatyoucanrollbacktothepointwheneverrequired.ThedifferentstatesofourtablecanbesavedatanytimeusingdifferentnamesandtherollbacktothatstatecanbedoneusingtheROLLBACKcommand.SAVEPOINT savepoint_name;UPDATE Student SET Name = 'Mini' WHERE Admno=105;SAVEPOINT A;
28. DISTINCT KeywordTheDISTINCTkeywordisusedalongwiththeSELECTcommandtoeliminateduplicaterowsinthetable.Thishelpstoeliminateredundantdata.ForExample:SELECT DISTINCT Place FROM Student;Willdisplaythefollowingdataasfollows:SELECT * FROM Student;OutputPlaceChennaiBangaloreDelhi
G-10 Computer SCienCe – XII
29. x=0 #globalvariable defadd(): globalx x=x+5 #incrementby2 print("Insideadd()functionxvalueis:",x) add() print("Inmainxvalueis:",x) Output: Insideadd()functionxvalueis:5 Inmainxvalueis:530. •Lambdafunctionismostlyusedforcreatingsmallandone-timeanonymousfunction. • Lambdafunctionsaremainlyusedincombinationwiththefunctionslikefilter(),map()
andreduce(). 31. (i)Toautomatecertaintasksinaprogram.
(ii)Extractinginformationfromadataset. (iii)Lesscodeintensiveascomparedtotraditionalprogramminglanguage. 32. #Programtojointwotuples Tup1=(2,4,6,8,10) Tup2=(1,3,5,7,9) Tup3=Tup1+Tup2 print(Tup3) Output (2,4,6,8,10,1,3,5,7,9) 33. Output: 246810
PART - III
34(a) Excel CSV
1. Excelisabinaryfilethatholdsinformationaboutalltheworksheetsinafile,includingbothcontentandformatting.
CSVformatisaplaintextformatwithaseriesofvaluesseparatedbycommas.
2. XLSfilescanonlybereadbyapplicationsthathavebeenespeciallywrittentoreadtheirformat,andcanonlybewritteninthesameway.
CSVcanbeopenedwithanytexteditorinWindowslikenotepad,MSExcel,OpenOffice,etc.
3. Excelisaspreadsheetthatsavesfilesintoitsownproprietaryformatviz.xlsorxlsx.
CSVisaformatforsavingtabularinformationintoadelimitedtextfilewithextension.csv
4. Excelconsumesmorememorywhileimportingdata.
ImportingCSVfilescanbemuchfaster,anditalsoconsumeslessmemory.
ANSWERS G-11
[OR] (b) ThesyntaxtoexecutethePythonprogramis
Python <filename.py> -i <C++ filename without cpp extension>Where,Python keywordtoexecutethePythonprogramfromcommandlinefilename.py NameofthePythonprogramtoexecuted-i inputmodeC++filenamewithout nameofC++filetobecompiledandexecutedcppextensionForexampletypePythonpycpp.py-ipaliinthecommandpromptandpressenterkey.Ifthecompilationissuccessfulyouwillgetthedesiredoutput.Otherwisetheerrorwillbedisplayed.
35(a) MyList=[1,3,5,7,9] print("ListOddnumbers...") forxinMyList: print(x) MyList[0:5]=2,4,6,8,10 print("ListEvennumbers...") foryinMyList: print(y) Output ListOddnumbers... 1 3 5 7 9 ListEvennumbers... 2 4 6 8 10
[OR]
(b) The range( ) is a functionused togenerate a seriesofvalues inPython.Using range ( )function,youcancreatelistwithseriesofvalues.Therange()functionhasthreearguments.
Syntax of range ( ) function: range (start value, end value, step value) where,
• startvalue–beginningvalueofseries.Zeroisthedefaultbeginningvalue. • endvalue–upperlimitofseries.Pythontakestheendingvalueasupperlimit–1.
G-12 Computer SCienCe – XII
• stepvalue–Itisanoptionalargument,whichisusedtogeneratedifferentintervalofvalues.
Example : Generating whole numbers upto 10 forxinrange(1,11): print(x) Output 1 2 3 4 5 6 7 8 9 10 36(a) 1.(12,78,91,"Tamil","Telugu",3.14,69.48)
2. (91,"Tamil","Telugu") 3. (12,78,91,"Tamil","Telugu") 4. ("Telugu",3.14,69.48) 5. (12,78,91,"Tamil","Telugu",3.14,69.48)
[OR] (b) (2,4,6,8,10) NameError:name"T"notdefined. 37(a)
Algorithm Program1. Algorithmhelpstosolveagivenproblem
logicallyanditcanbecontrastedwiththeprogram.
Programisanexpressionofalgorithminaprogramminglanguage.
2. Algorithmcanbecategorizedbasedontheirimplementationmethods,designtechniquesetc.
Algorithmcanbeimplementedbystructuredorobjectorientedprogrammingapproach.
3. Thereisnospecificrulesforalgorithmwritingbutsomeguidelinesshouldbefollowed.
Programshouldbewrittenfortheselectedlanguagewithspecificsyntax.
4. Algorithmresemblesapseudocodewhichcanbeimplementedinanylanguage.
Programismorespecifictoaprogramminglanguage.
[OR] (b) • Input:Zeroormorequantitiestobesupplied. • Output:Atleastonequantityisproduced. • Finiteness:Algorithmsmustterminateafterfinitenumberofsteps.
ANSWERS G-13
• Definiteness:Alloperationsshouldbewelldefined.Forexampleoperationsinvolvingdivisionbyzeroortakingsquarerootfornegativenumberareunacceptable.
• Effectiveness:Everyinstructionmustbecarriedouteffectively. • Correctness:Thealgorithmsshouldbeerrorfree. • Simplicity:Easytoimplement. • Unambiguous:Algorithmshouldbeclearandunambiguous.Eachofitsstepsandtheir
inputs/outputsshouldbeclearandmustleadtoonlyonemeaning. • Feasibility:Shouldbefeasiblewiththeavailableresources. • Portable:Analgorithmshouldbegeneric,independentofanyprogramminglanguageor
anoperatingsystemabletohandleallrangeofinputs. • Independent: An algorithm should have step-by-step directions, which should be
independentofanyprogrammingcode. 38(a) Literalisarawdatagiveninavariableorconstant.InPython,therearevarioustypesof
literals. (i)Numeric (ii)String (iii)Boolean
(i) Numeric Literals:NumericLiteralsconsistsofdigitsandareimmutable(unchangeable).Numericliteralscanbelongto3differentnumericaltypesInteger,FloatandComplex.
To demonstrate Numeric literals#ProgramtodemonstrateNumericLiterals a=0b1010 #BinaryLiterals b=100 #DecimalLiteral c=0o310 #OctalLiteral d=0x12c #HexadecimalLiteral print("IntegerLiterals:",a,b,c,d) #FloatLiteral float_1=10.5 float_2=1.5e2 print("FloatLiterals:",float_1,float_2) #ComplexLiteral x=1+3.14j print("ComplexLiterals:",x) Print("x=",x,"Imaginarypartofx=",x.imag,"Realpartofx=",x.real) #EndoftheProgram Output: IntegerLiterals:10100200300 FloatLiterals:10.5150.0 ComplexLiterals: x=(1.3.14)Imaginarypartofx=3.14Realpartof9x=1.0 (ii) String Literals:InPythonastringliteralisasequenceofcharacterssurroundedby
quotes.Pythonsupportssingle,doubleandtriplequotesforastring.Acharacterliteralisasinglecharactersurroundedbysingleordoublequotes.Thevaluewithtriple-quote"''"isusedtogivemultilinestringliteral.
(iii) Boolean Literals:ABooleanliteralcanhaveanyofthetwovalues:TrueorFalse. (iv) Escape Sequences: InPython strings, thebackslash "\" is a special character, also
G-14 Computer SCienCe – XII
calledthe"escape"character.Itisusedinrepresentingcertainwhitespacecharacters:"\t" isa tab,"\n" isanewline,and"\r" isacarriagereturn.Forexampletoprint themessage"It’sraining",thePythoncommandis
>>>print("It\’srainning") It’srainning Pythonsupportsthefollowingescapesequencecharacters.
Escape sequencecharacter Description Example Output
\\ Backslash >>>print("\\test") \test\’ Single-quote >>>print("Doesn\'t") Doesn't
[OR] (b) Tokens
PythonbreakseachlogicallineintoasequenceofelementarylexicalcomponentsknownasTokens. Thenormaltokentypesare (i)Identifiers (ii)Keywords (iii)Operators (iv)Delimiters (v)Literals.Whitespaceseparationisnecessarybetweentokens,identifiersorkeywords.(i) IdentifiersAnIdentifierisanameusedtoidentifyavariable,function,class,moduleorobject.•Anidentifiermuststartwithanalphabet(A..Zora..z)orunderscore(_).•Identifiersmaycontaindigits(0..9)•Pythonidentifiersarecasesensitivei.e.uppercaseandlowercaselettersaredistinct.•Identifiersmustnotbeapythonkeyword.•Pythondoesnotallowpunctuationcharactersuchas%,$,@etc.,withinidentifiers.Example of valid identifiers Sum,total_marks,regno,num1Example of invalid identifiers 12Name,name$,total-mark,continue(ii) KeywordsKeywordsarespecialwordsusedbyPythoninterpretertorecognizethestructureofprogram.Asthesewordshavespecificmeaningforinterpreter,theycannotbeusedforanyotherpurpose.
Python’sKeywordsfalse class finally is returnnone continue for lambda trytrue def from nonlocal whileand del global not withas elif If or yieldassert else import passbreak except In raise
ANSWERS G-15
(iii) OperatorsIn computer programming languages operators are special symbolswhich representcomputations,conditionalmatchingetc.Thevalueofanoperatorusediscalledoperands. Operators are categorized asArithmetic,Relational,Logical,Assignment etc.Value andvariableswhenusedwithoperatorareknownasoperands.Arithmetic operatorsAnarithmeticoperatorisamathematicaloperatorthattakestwooperandsandperformsacalculationonthem.Theyareusedforsimplearithmetic.Mostcomputerlanguagescontainasetofsuchoperatorsthatcanbeusedwithinequationstoperformdifferenttypesofsequentialcalculations.PythonsupportsthefollowingArithmeticoperators.
Operator - Operation Examples ResultAssumea=100andb=10.Evaluatethefollowingexpressions+(Addition) >>>a+b 110-(Subtraction) >>>a–b 90*(Multiplication) >>>a*b 1000/(Divisioin) >>>a/b 10.0%(Modulus) >>>a%30 10**(Exponent) >>>a**2 10000//(FloorDivision) >>>a//30(IntegerDivision) 3
Relational or Comparative operatorsARelationaloperatorisalsocalledasComparative operatorwhichcheckstherelationshipbetweentwooperands.Iftherelationistrue,itreturnsTrue;otherwiseitreturnsFalse.
Operator - Operation Examples ResultAssumethevalueofa=100andb=35.Evaluatethefollowingexpressions.==(isEqual) >>>a==b False>(Greaterthan) >>>a>b True<(Lessthan) >>>a<b False>=(GreaterthanorEqualto) >>>a>=b True<=(LessthanorEqualto) >>>a<=b False!=(Notequalto) >>>a!=b True
Logical operatorsInpython,Logicaloperatorsareusedtoperformlogicaloperationsonthegivenrelationalexpressions.Therearethreelogicaloperatorstheyareand, or andnot.
Operator Example ResultAssumea=97andb=35,EvaluatethefollowingLogicalexpressionsor >>>a>bora==b Trueand >>>a>banda==b Falsenot >>>nota>b False(i.e.)NotTrue
G-16 Computer SCienCe – XII
Assignment operatorsInPython,=isasimpleassignmentoperatortoassignvaluestovariable.Leta=5andb=10assignsthevalue5toaand10tobthesetwoassignmentstatementcanalsobegivenasa,b=5,10thatassignsthevalue5and10ontherighttothevariablesaandbrespectively.TherearevariouscompoundoperatorsinPythonlike+=,-=,*=,/=,%=,**=and//=arealsoavailable.
Operator Description ExampleAssumex=10= Assignsrightsideoperandstoleftvariable >>>x=10
>>>b="Computer"+= Addedandassignbacktheresulttoleftoperandi.e.
x=30>>>x+=20#x=x+20
–= Subtractedandassignbacktheresulttoleftoperandi.e.x=25
>>>x–=5#x=x–5
*= Multipliedandassignbacktheresulttoleftoperandi.e.x=125
>>>x*=5#x=x*5
/= Dividedandassignbacktheresulttoleftoperandi.e.x=62.5
>>>x/=2#x=x/2
%= Takenmodulus(Remainder)using twooperandsandassigntheresulttoleftoperandi.e.x=2.5
>>>x%=3#x=x%3
**= Performedexponential(power)calculationonoperatorsandassignvaluetotheleftoperandi.e.x=6.25
>>>x**=2#x=x**2
//= Performed floor division on operators and assignvaluetotheleftoperandi.e.x=2.0
>>>x//=3
Conditional operatorTernaryoperatorisalsoknownasconditionaloperatorthatevaluatesomethingbasedonaconditionbeingtrueorfalse.Itsimplyallowstestingaconditioninasinglelinereplacingthemultilineif-elsemakingthecodecompact.TheSyntaxconditionaloperatoris, Variable Name = [on_true] if [Test expression] else [on_false] Example : min=50if49<50else70#min=50 min=50if49>50else70#min=70(iv) DelimitersPython uses the symbols and symbol combinations as delimiters in expressions, lists,dictionariesandstrings.Followingarethedelimiters.
( ) [ ] { }, : . ' = ;+= –= *= /= //= %=&= |= ^= >>= <<= **=
ANSWERS G-17
(v) LiteralsLiteralisarawdatagiveninavariableorconstant.InPython,therearevarioustypesofliterals. (i)Numeric (ii)String (iii)BooleanNumeric LiteralsNumericLiteralsconsistsofdigitsandareimmutable(unchangeable).Numericliteralscanbelongto3differentnumericaltypesInteger,FloatandComplex.String LiteralsInPythonastringliteralisasequenceofcharacterssurroundedbyquotes.Pythonsupportssingle,doubleandtriplequotesforastring.Acharacterliteralisasinglecharactersurroundedbysingleordoublequotes.Thevaluewithtriple-quote'"'"isusedtogivemulti-linestringliteral.Boolean LiteralsABooleanliteralcanhaveanyofthetwovalues:TrueorFalse.Escape SequencesInPythonstrings,thebackslash"\"isaspecialcharacter,alsocalledthe"escape"character.Itisusedinrepresentingcertainwhitespacecharacters:"\t"isatab,"\n"isanewline,and"\r"isacarriagereturn.Forexampletoprintthemessage"It’sraining",thePythoncommandis >>> print ("It\’s rainning") It’s rainningPythonsupportsthefollowingescapesequencecharacters.
Escape sequence character
Description Example Output
\\ Backslash >>>print("\\test") \test\' Single-quote >>>print("Doesn\'t") Doesn't\" Double-quote >>>print("\"Python\"") "Python"\n Newline print("Python","\n","Lang..") PythonLang..\t Tab print("Python","\t","Lang..") PythonLang..
Sample Paper-6PART - III
25. num1=int(input("Enterfirstnumber:")) num2=int(input("Entersecondnumber:")) num3=int(input("Enterthirdnumber:")) if(num1<num2)and(num1<num3): smallest=num1 elif(num2<num1)and(num2<num3): smallest=num2 else: smallest=num3 print("Thesmallestnumberis",smallest) Output: Enterfirstnumber:12
G-18 Computer SCienCe – XII
Entersecondnumber:7 Enterthirdnumber:15 Thesmallestnumberis7 26. output:
weoo1 27. (i)Functionshelpustodivideaprogramintomodules.Thismakesthecodeeasierto manage.
(ii) Itimplementscodereuse.Everytimeyouneedtoexecuteasequenceofstatements,allyouneedtodoistocallthefunction.
(iii) Functions, allows us to change functionality easily, and different programmers canworkondifferentfunctions.
28. Program:str1="COMPUTER"index=len(str1)foriinstr1: print(str1[:index])
index–=1 29. InPython,append()functionisusedtoaddasingleelementandextend()functionisused
toaddmorethanoneelementtoanexistinglist. Syntax: List.append(elementtobeadded) List.extend([elementstobeadded]) 30. Inthebelowexample,Mylistcontainsanotherlistasanelement.Thistypeoflistisknown
as"NestedList". Nestedlistisalistcontaininganotherlistasanelement. Example:Mylist=["Welcome",3.14,10,[2,4,6]] 31. Listisconstructedbyplacingexpressionswithinsquarebracketsseparatedbycommas.Such
anexpressioniscalledalistliteral.Listcanstoremultiplevalues.Eachvaluecanbeofanytypeandcanevenbeanotherlist.
ExampleforListis[10,20]. Representing Rational Numbers Using List Youcannowrepresentarationalnumberasapairoftwointegersinpseudocode:anumerator
andadenominator. rational(n,d): return[n,d] numer(x): returnx[0] denom(x): returnx[1] 32. Local Scope
Localscopereferstovariablesdefinedincurrentfunction.Always,afunctionwillfirstlookupforavariablenameinitslocalscope.Onlyifitdoesnotfinditthere,theouterscopesarechecked.
ANSWERS G-19
Lookatthisexample1. Disp():
2. a:=7
3. printa
4.Disp()
Entireprogram OutputoftheProgram
Disp():a:=7printa
Disp()
7
Onexecutionoftheabovecodethevariableadisplaysthevalue7,becauseitisdefinedandavailableinthelocalscope.
33. • false • none • true • and • as • assert
PART - IV 34(a) (i)Startwiththemiddleelement: • Ifthesearchelementisequaltothemiddleelementofthearrayi.e.,themiddlevalue
=numberofelementsinarray/2,thenreturntheindexofthemiddleelement. • Ifnot,thencomparethemiddleelementwiththesearchvalue, • Ifthesearchelementisgreaterthanthenumberinthemiddleindex,thenselectthe
elementstotherightsideofthemiddleindex,andgotoStep-1. • If the search element is less than the number in themiddle index, then select the
elementstotheleftsideofthemiddleindex,andstartwithStep-1. (ii) Whenamatchisfound,displaysuccessmessagewiththeindexoftheelementmatched. (iii) Ifnomatchisfoundforallcomparisons,thendisplayunsuccessfulmessage.
[OR]
(b) Step1−Ifitisthefirstelement,itisalreadysorted. Step2−Picknextelement. Step3−Comparewithallelementsinthesortedsub-list. Step4−Shiftalltheelementsinthesortedsub-listthatisgreaterthanthevaluetobesorted Step5−Insertthevalue Step6−Repeatuntillistissorted 35(a) input() function: InPython,input()functionisusedtoacceptdataasinputatruntime.Thesyntaxforinput()
functionis,Variable = input ("prompt string")
G-20 Computer SCienCe – XII
Where,promptstringinthesyntaxisastatementormessagetotheuser,toknowwhatinputcanbegiven.
Ifapromptstringisused,itisdisplayedonthemonitor;theusercanprovideexpecteddatafromtheinputdevice.Theinput() takeswhatever is typedfromthekeyboardandstorestheentereddatainthegivenvariable.Ifpromptstringisnotgivenininput()nomessageisdisplayedonthescreen,thus,theuserwillnotknowwhatistobetypedasinput.
Example: input( ) with prompt string >>>city=input("EnterYourCity:") EnterYourCity:Madurai >>>print("Iamfrom",city) IamfromMadurai Example: input( ) without prompt string >>>city=input() Rajarajan >>>print("Iamfrom",city) IamfromRajarajan Notethatinexample-2,theinput( )isnothavinganypromptstring,thustheuserwillnot
knowwhatistobetypedasinput.Iftheuserinputsirrelevantdataasgivenintheaboveexample,thentheoutputwillbeunexpected.So,tomakeyourprogrammoreinteractive,providepromptstringwithinput( ).
The input ( )acceptsalldataasstringorcharactersbutnotasnumbers.Ifanumericalvalueisentered,theinputvaluesshouldbeexplicitlyconvertedintonumericdatatype.Theint ( )functionisusedtoconvertstringdataasintegerdataexplicitly.Wewilllearnaboutmoresuchfunctionsinlaterchapters.
Example : x=int(input("EnterNumber1:")) y=int(input("EnterNumber2:")) print("Thesum=",x+y) Output: EnterNumber1:34 EnterNumber2:56 Thesum=90 Example : Alternate method for the above program x,y=int(input("EnterNumber1:")),int(input("EnterNumber2:")) print("X=",x,"Y=",y) Output: EnterNumber1:30 EnterNumber2:50 X=30Y=50
[OR]
ANSWERS G-21
(b) Components of SQLSQL commands are divided into five categories:
a. Data Definition LanguageTheDataDefinitionLanguage(DDL)consistofSQLstatementsusedtodefinethedatabasestructureorschema.Itsimplydealswithdescriptionsofthedatabaseschemaandisusedtocreateandmodifythestructureofdatabaseobjectsindatabases.SQL commands which comes under Data Definition Language are:
Create Tocreatetablesinthedatabase.Alter Altersthestructureofthedatabase.Drop Deletetablesfromdatabase.Truncate Remove all records from a table, also release the space occupied by those
records.b. Data Manipulation LanguageADataManipulationLanguage(DML)isacomputerprogramminglanguageusedforadding(inserting),removing(deleting),andmodifying(updating)datainadatabase.SQL commands which comes under Data Manipulation Language are :
Insert InsertsdataintoatableUpdate Updatestheexistingdatawithinatable.Delete Deletesallrecordsfromatable,butnotthespaceoccupiedbythem.
c. Data Control Language:ADataControlLanguage(DCL)isusedforcontrollingprivilegesinthedatabase
SQLcommands:GRANT,REVOKEd. Transactional Control Language;Transactionalcontrollanguage(TCL)isusedtomanagetransactionsi.e.changesmadetothedatainthedatabase.SQLcommands:COMMIT,ROLLBACK,SAVEPOINT.
e. Data Query LanguageTheDataQueryLanguage(DQL)havecommandstoqueryorretrievedatafromthedatabase.SQLcommands:SELECT.
G-22 Computer SCienCe – XII
36(a) classLibrary: def__init__(self): self.bookname="" self.author=”” defgetdata(self): self.bookname=input("EnterNameoftheBook:") self.author=input("EnterAuthoroftheBook:") defdisplay(self): print("NameoftheBook:",self.bookname) print("AuthoroftheBook:",self.author) print("\n") book=[]#emptylist ch='y' while(ch=='y'): print("1.AddNewBook\n2.DisplayBooks") resp=int(input("Enteryourchoice:")) if(resp==1): L=Library() L.getdata() book.append(L) elif(resp==2): forxinbook: x.display() else: print("Invalidinput....") ch=input("Doyouwantcontinue....") Output: 1.AddNewBook 2.DisplayBooks Enteryourchoice:1 EnterNameoftheBook:ProgramminginC++ EnterAuthoroftheBook:K.Kannan Doyouwantcontinue....y 1.AddNewBook 2.DisplayBooks Enteryourchoice:1 EnterNameoftheBook:LearnPython EnterAuthoroftheBook:V.G.Ramakrishnan Doyouwantcontinue....y 1.AddNewBook 2.DisplayBooks Enteryourchoice:1
ANSWERS G-23
EnterNameoftheBook:AdvancedPython EnterAuthoroftheBook:Dr.Vidhya Doyouwantcontinue....y 1.AddNewBook 2.DisplayBooks Enteryourchoice:1 EnterNameoftheBook:WorkingwithOpenOffice EnterAuthoroftheBook:N.V.Gowrisankar Doyouwantcontinue....y 1.AddNewBook 2.DisplayBooks Enteryourchoice:1 EnterNameoftheBook:DataStructure EnterAuthoroftheBook:K.Lenin Doyouwantcontinue....y 1.AddNewBook 2.DisplayBooks Enteryourchoice:1 EnterNameoftheBook:AnIntroductiontoDatabaseSystem EnterAuthoroftheBook:R.Sreenivasan Doyouwantcontinue....y 1.AddNewBook 2.DisplayBooks Enteryourchoice:2 NameoftheBook:ProgramminginC++ AuthoroftheBook:K.Kannan NameoftheBook:LearnPython AuthoroftheBook:V.G.Ramakrishnan NameoftheBook:AdvancedPython AuthoroftheBook:Dr.Vidhya NameoftheBook:WorkingwithOpenOffice AuthoroftheBook:N.V.Gowrisankar NameoftheBook:DataStructure AuthoroftheBook:K.Lenin NameoftheBook:AnIntroductiontoDatabaseSystem AuthoroftheBook:R.Sreenivasan Doyouwantcontinue....n
[OR] (b) classString: def__init__(self): self.uppercase=0 self.lowercase=0
G-24 Computer SCienCe – XII
self.vowels=0 self.consonants=0 self.spaces=0 self.string="" defgetstr(self): self.string=str(input("EnteraString:")) defcount_upper(self): forchinself.string: if(ch.isupper()): self.uppercase+=1 defcount_lower(self): forchinself.string: if(ch.islower()): self.lowercase+=1 defcount_vowels(self): forchinself.string: if(chin('A','a','e','E','i','I','o','O','l','L')): self.vowels+=1 defcount_consonants(self): forchinself.string: if(chnotin('A','a','e','E','i','I','o','O','l','L')): self.consonants+=1 defcount_space(self): forchinself.string: if(ch==""): self.spaces+=1 defexecute(self): self.count_upper() self.count_lower() self.count_vowels() self.count_consonants() self.count_space() defdisplay(self): print("Thegivenstringcontains...") print("%dUppercaseletters"%self.uppercase) print("%dLowercaseletters"%self.lowercase) print("%dVowels"%self.vowels) print("%dConsonants"%self.consonants) print("%dSpaces"%self.spaces) S=String() S.getstr() S.execute()
ANSWERS G-25
S.display() Output: EnteraString:WelcomeToLearnComputerScience Thegivenstringcontains... 5Uppercaseletters 24Lowercaseletters 13Vowels 20Consonants 4Spaces 37(a) ThegetoptmoduleofPythonhelpsyoutoparse(split)command-lineoptionsandarguments.
Thismoduleprovidestwofunctionstoenablecommand-lineargumentparsing. getopt.getopt method Thismethodparsescommand-lineoptionsandparameterlist.Followingisthesyntaxfor
thismethod−<opts>,<args>=getopt.getopt(argv, options, [long_options])
Hereisthedetailoftheparameters− argv− Thisistheargumentlistofvaluestobeparsed(splited).Inourprogramthe
completecommandwillbepassedasalist. options− ThisisstringofoptionlettersthatthePythonprogramrecognizeas,for
inputorforoutput,withoptions(like'i'or'o')thatfollowedbyacolon(:).Herecolonisusedtodenotethemode.
long_options− Thisparameterispassedwithalistofstrings.ArgumentofLongoptionsshould be followedby an equal sign ('='). In our program theC++filenamewill be passed as string and 'i' alsowill be passed alongwith toindicateitastheinputfile.
getopt()methodreturnsvalueconsistingoftwoelements.Eachofthesevaluesarestoredseparatelyintwodifferentlist(arrays)optsandargs.Optscontainslistofsplittedstringslikemode,pathandargscontainsanystringifatallnotsplittedbecauseofwrongpathormode.argswillbeanemptyarrayifthereisnoerrorinsplittingstringsbygetopt().
ForexampleThePythoncodewhichisgoingtoexecutetheC++filep4incommandlinewillhavethegetopt()methodlikethefollowingone.
opts,args=getopt.getopt(argv,"i:",['ifile='])whereoptscontains [('–i','c:\\pyprg\\p4')]–i:– optionnothingbutmodeshouldbefollowedby:'c:\\pyprg\\p4' valuenothingbuttheabsolutepathofC++file.
In our examples since the entire command line commands are parsed and no leftoverargument, the second argument args will be empty []. If args is displayed using print()commanditdisplaystheoutputas[].
>>>print(args) []
[OR] (b) SQLiteisasimplerelationaldatabasesystem,whichsavesitsdatainregulardatafilesor
evenintheinternalmemoryofthecomputer.Itisdesignedtobeembeddedinapplications,
G-26 Computer SCienCe – XII
insteadofusinga separatedatabaseserverprogramsuchasMySQLorOracle.SQLite isfast,rigorouslytested,andflexible,makingiteasiertowork.PythonhasanativelibraryforSQLite.TouseSQLite,Step1 importsqlite3Step2 createaconnectionusingconnect()methodandpassthenameofthedatabaseFileStep3 Setthecursorobjectcursor=connection.cursor()
•Connectingtoadatabaseinstep2meanspassingthenameofthedatabasetobeaccessed.Ifthedatabasealreadyexiststheconnectionwillopenthesame.Otherwise,Pythonwillopenanewdatabasefilewiththespecifiedname.
•Cursorinstep3:isacontrolstructureusedtotraverseandfetchtherecordsofthedatabase.•CursorhasamajorroleinworkingwithPython.Allthecommandswillbeexecutedusingcursorobjectonly.
Tocreateatableinthedatabase,createanobjectandwritetheSQLcommandinit. Example:-sql_comm="SQLstatement"
Forexecutingthecommandusethecursormethodandpasstherequiredsqlcommandasaparameter.Manynumberofcommandscanbestoredinthesql_commandcanbeexecutedoneafterother.Anychangesmadeinthevaluesoftherecordshouldbesavedbythecommand"Commit"beforeclosingthe"Tableconnection".
38(a) importsqlite3connectoin=sqlite3.connect("company.db")cursor=connection.cursor()cursor.execute("Select*fromproduct")print("DisplayingRecords")result=cursor.fetchmany(5)print(*result,Sep="\n")Output:Displayingrecords(1003,'Scanner',10500)(1004,'Speaker',3000)(1005,'Printer',8000)(1008,'Monitor',15000)(1010,'Mouse',700)
[OR]
(b) Read a CSV File Using PythonTherearetwowaystoreadaCSVfile.(i)Usethecsvmodule’sreaderfunction(ii)UsetheDictReaderclass.
ANSWERS G-27
Ways to read CSV file
CSV Module’s Reader FunctionYoucanreadthecontentsofCSVfilewiththehelpofcsv.reader()method.Thereaderfunctionisdesignedtotakeeachlineofthefileandmakealistofallcolumns.Then,youjustchoosethecolumnyouwantthevariabledatafor.Usingthismethodonecanreaddatafromcsvfilesofdifferentformatslikequotes(""),pipe(|)andcomma(,).The syntax for csv.reader() is csv.reader(fileobject,delimiter,fmtparams)wherefileobject:- passesthepathandthemodeofthefiledelimiter:- anoptional parametercontaining thestandarddilects like, Ietccanbe
omittedfmtparams: optionalparameterwhichhelptooverridethedefaultvaluesofthedialects
likeskipinitialspace,quotingetc.Canbeomitted
CSV file with default delimiter comma(,)Thefollowingprogramreadafilecalled"samplel.csv"withdefaultdelimitercomma(,)andprintrowbyrow.#importingcsvimportcsv#opening the csv file which is in different location with read modewithopen('c:\\pyprg\\samplel.csv','r')asF:#other way to open the file is f= ( 'c:\\pyprg\\sample 1.csv', 'r') reader=csv.reader(F)#printing each line of the Data row by row
G-28 Computer SCienCe – XII
print(row) F.close()OUTPUT ['SNO','NAME','CITY'] ['12101','RAM','CHENNAI'] ['12102','LAVANYA','TIRUCHY'] ['12103','LAKSHMAN','MADURAI']CSV files- data with Spaces at the beginningConsiderthefollowingfile“sample2.csv”containingthefollowingdatawhenopenedthroughnotepad
Topic l Topic 2 Topic 3one two threeExample1 Example2 Example3ThefollowingprogramreadthefilethroughPythonusing“csv.reader()”.importcsvcsv.register_dialect('myDialect',delimiter=',',skipinitialspace=True)F=open('c:\\pyprg\\sample2.csv','r')reader=csv.reader(F,dialect='myDialect’)forrowinreader: print(row)F.close()OUTPUT['Topic1','Topic2','Topic3']['one','two','three']['Example1','Example2','Example3']Asyoucanseein"sample2.csv"therearespacesafterthedelimiterduetowhichtheoutputisalsodisplayedwithspaces.Thesewhitespacescanberemoved,byregisteringnewdialectsusingcsv.register_dialect()classofcsvmodule.Adialectdescribestheformatofthecsvfilethatistoberead.Indialectstheparameterskipinitialspace"isusedforremovingwhitespacesafterthedelimiter.CSV File-Data With QuotesYoucanreadthecsvfilewithquotes,byregisteringnewdialectsusingcsv.register_dialect()classofcsvmodule.Here,wehavequotes.csvfilewithfollowingdata.SNO,Quotes(a)"Thesecrettogettingaheadisgettingstarted."(b)"Excellenceisacontinuousprocessandnotanaccident."(c)"Workharddreambignevergiveupandbelieveyourself."(d)"Failureistheopportunitytobeginagainmoreintelligently."(e)"Thesuccessfulwarrioristheaverageman,withlaser-likefocus."
ANSWERS G-29
ThefollowingProgramread"quotes.csv"file,wheredelimiteriscomma(,)butthequotesarewithinquotes("").importcsvcsv.register_dialect('myDialect',delimiter=',',quoting=csv.QUOTE_ALL,skipinitialspace=True)f=open('c:\\pyprg\\quotes.csv','r')reader=csv.reader(f,dialect='myDialect')forrowinreader: print(row)OUTPUT ['SNO','Quotes'][(a),'Thesecrettogettingaheadisgettingstarted.'][(b),'Excellenceisacontinuousprocessandnotanaccident.'][(c),'Workharddreambignevergiveupandbelieveyourself.'][(d),'Failureistheopportunitytobeginagainmoreintelligently.'][(e),'Thesuccessfulwarrioristheaverageman,withlaser-likefocus.']Intheaboveprogram,registeradialectwithnamemyDialect.Then,weusedcsv. QUOTE_ALL to display all the charactersafterdoublequotes.CSV files with Custom DelimitersYou can read CSV file having custom delimiter by registering a new dialect with the help of csv.register_dialect().Inthefollowingfilecalled"sample4.csv",eachcolumnisseparatedwith|(Pipesymbol)
Roll No Name City12101 Arun Chennai12102 Meena Kovai12103 Ram Nellai103 Ayush M104 Abinandh MThefollowingprogramreadthefile"sample4.csv"withuserdefineddelimiter"|"importcsv csv.register_dialect('myDialect',delimiter='|') withopen('c:\\pyprg\\sample4.csv','r')asf: reader=csv.reader(f,dialect='myDialect') forrowinreader: print(row)f.close()OUTPUT['RollNo','Name','City']['12101','Arun','Chennai']
G-30 Computer SCienCe – XII
['12102','Meena','Kovai']['12103','Ram','Nellai']Reading CSV File Into A DictionaryToreadaCSVfileintoadictionarycanbedonebyusingDictReader classofcsvmodulewhichworkssimilartothereader()classbutcreatesanobjectwhichmapsdatatoadictionary.Thekeysaregivenbythefieldnamesasparameter.DictReaderworksbyreadingthefirstlineoftheCSVandusingeachcommaseparatedvalueinthislineasadictionarykey.Thecolumnsineachsubsequentrowthenbehavelikedictionaryvaluesandcanbeaccessedwiththeappropriatekey(i.e.fieldname).IfthefirstrowofyourCSVdoesnotcontainyourcolumnnames,youcanpassafieldnamesparameterintotheDictReader’sconstructortoassignthedictionarykeysmanually.Themaindifferencebetweenthecsv.reader()andDictReader()isinsimpletermscsv.readerand csv.writerworkwith list/tuple,while csv.DictReader and csv.DictWriter workwithdictionary.csv.DictReaderandcsv.DictWritertakeadditionalargumentfieldnamesthatareusedasdictionarykeys.For Example Reading"sample8.csv"fileintoadictionaryimportcsvfilename='c:\\pyprg\\sample8.csv'input_file=csv.DictReader(open(filename;'r'))forrowininput_file: print(dict(row)) #dict() to print dataOUTPUT {'ItemName':'Keyboard','Quantity':'48'} {'ItemName':'Monitor','Quantity':'52'} {'ItemName':'Mouse','Quantity':'20'}Intheaboveprogram,DictReader()isusedtoread"sample8.csv"fileandmapintoadictionary.Then,thefunctiondict()isusedtoprintthedataindictionaryformatwithoutorder.Removethedict()functionfromtheaboveprogramanduseprint(row).Checkyouaregettingthefollowingoutput OrderedDict([('ItemName','Keyboard'),('Quantity','48')]) OrderedDict([('ItemName','Monitor'),('Quantity','52')]) OrderedDict([('ItemName','Mouse'),('Quantity','20')])
Sample Paper-7PART - III
25. (a) A Priori estimates:Thisisatheoreticalperformanceanalysisofanalgorithm.Efficiencyofanalgorithmismeasuredbyassumingtheexternalfactors.
(b) A Posteriori testing:Thisiscalledperformancemeasurement.Inthisanalysis,actualstatisticslikerunningtimeandrequiredforthealgorithmexecutionsarecollected.
26. Anarithmeticoperatorisamathematicaloperatorthattakestwooperandsandperformsacalculationonthem.Theyareusedforsimplearithmetic.Mostcomputerlanguagescontaina
ANSWERS G-31
setofsuchoperatorsthatcanbeusedwithinequationstoperformdifferenttypesofsequentialcalculations.
27. InPython,commentsbeginwithhashsymbol(#).Thelinesthatbeginswith#areconsideredas comments and ignoredby thePython interpreter.Commentsmaybe single lineornomulti-lines.Themultilinecommentsshouldbeenclosedwithinasetof#asgivenbelow.
# It is Single line Comment # It is multiline comment which contains more than one line #
28. for each itemin sequence
Yes
No
Body of for
Exit loop
Last itemreached?
29. Output: 12
30. Syntax: Syntax: break continue
Condition
break?
no
Enter loop
false
true
yes
Exit
loop
Remaining body of loop
Test Expression of loop
continue?
no
Enter loop
false
true
yes
Exit
loop
Remaining body of loop
Syntax: pass 31.
String S C H O O LPositivesubscript 0 1 2 3 4 5Negativesubscript –6 –5 –4 –3 –2 –1
32. Syntax: del List [index of an element] #todeleteaparticularelement
G-32 Computer SCienCe – XII
del List [index from : index to] #todeletemultipleelements del List #todeleteentirelist 33. Output: Error:SamplehasnoattributeS.___num 10
PART - IV 34(a) Basically,ascriptisatextfilecontainingthePythonstatements.PythonScriptsarereusable
code.Oncethescriptiscreated,itcanbeexecutedagainandagainwithoutretyping.TheScriptsareeditable.
Creating Scripts in Python (i) ChooseFile→NewFileorpressCtrl+NinPythonshellwindow.
(ii) Anuntitledblankscripttexteditorwillbedisplayedonscreen
ANSWERS G-33
(iii) TypethefollowingcodeinScripteditor
a=100 b=350 c=a+b print("TheSum=",c)Saving Python Script(i) ChooseFile→SaveorPressCtrl+S
(ii) Now,SaveAsdialogboxappearsonthescreen
(iii) IntheSaveAsdialogbox,selectthelocationwhereyouwanttosaveyourPythoncode,andtypethefilenameinFileNamebox.Pythonfilesarebydefaultsavedwithextension.py.Thus,whilecreatingPythonscriptsusingPythonScripteditor,noneedtospecifythefileextension.
(iv) Finally,clickSavebuttontosaveyourPythonscript.
G-34 Computer SCienCe – XII
Executing Python Script(i) ChooseRun→RunModuleorPressF5
(ii) Ifyourcodehasanyerror,itwillbeshowninredcolorintheIDLEwindow,andPythondescribesthetypeoferroroccurred.Tocorrecttheerrors,gobacktoScripteditor,makecorrections,savethefileusingCtrl+SorFile→Saveandexecuteitagain.
(iii) Forallerrorfreecode,theoutputwillappearintheIDLEwindowofPython
[OR]
(b) Input and Output FunctionsAprogramneedstointeractwiththeusertoaccomplishthedesiredtask;thiscanbeachievedusingInput-Output functions.Theinput()functionhelpstoenterdataatruntimebytheuserandtheoutputfunctionprint()isusedtodisplaytheresultoftheprogramonthescreenafterexecution.The print() functionInPython,theprint()functionisusedtodisplayresultonthescreen.Thesyntaxforprint() isasfollows:Example print("stringtobedisplayedasoutput") print(variable) print("Stringtobedisplayedasoutput",variable) print("String1",variable,"String2",variable,"String3"……)
ANSWERS G-35
Example >>>print("WelcometoPythonProgramming") WelcometoPythonProgramming >>>x=5 >>>y=6 >>>z=x+y >>>print(z) 11 >>>print("Thesum=",z) Thesum=11 >>>print("Thesumof",x,"and",y,"is",z) Thesumof5and6is11Thprint ( )evaluatestheexpressionbeforeprintingitonthemonitor.Theprint()displaysanentirestatementwhichisspecifiedwithinprint().Comma ( , )isusedasaseparatorinprint()toprintmorethanoneitem.input() functionInPython,input( )functionisusedtoacceptdataasinputatruntime.Thesyntaxforinput() functionis, Variable=input("promptstring")Where,prompt stringinthesyntaxisastatementormessagetotheuser,toknowwhatinputcanbegiven.Ifapromptstringisused,itisdisplayedonthemonitor;theusercanprovideexpecteddatafromtheinputdevice.The input( ) takeswhateveris typedfromthekeyboardandstorestheentereddatainthegivenvariable.Ifpromptstringisnotgivenininput( )nomessageisdisplayedonthescreen,thus,theuserwillnotknowwhatistobetypedasinput. Example 1: input( ) with prompt string >>>city=input("EnterYourCity:") EnterYourCity:Madurai >>>print("Iamfrom",city) IamfromMadurai Example 2: input( ) without prompt string >>>city=input() Rajarajan >>>print("Iamfrom",city) IamfromRajarajanNotethatinexample-2,theinput( )isnothavinganypromptstring,thustheuserwillnotknowwhatistobetypedasinput.Iftheuserinputsirrelevantdataasgivenintheaboveexample,thentheoutputwillbeunexpected.So,tomakeyourprogrammoreinteractive,providepromptstringwithinput( ).Theinput ( )acceptsalldataasstringorcharactersbutnotasnumbers.Ifanumericalvalueisentered,theinputvaluesshouldbeexplicitlyconvertedintonumericdatatype.Theint()function
G-36 Computer SCienCe – XII
isusedtoconvertstringdataasintegerdataexplicitly.Wewilllearnaboutmoresuchfunctionsinlaterchapters. Example 3: x=int(input("EnterNumber1:")) y=int(input("EnterNumber2:")) print("Thesum=",x+y) Output: EnterNumber1:34 EnterNumber2:56 Thesum=90 Example 4: Alternate method for the above program x,y=int(input("EnterNumber1:")),int(input("EnterNumber2:")) print("X=",x,"Y=",y) Output: EnterNumber1:30 EnterNumber2:50 X=30Y=50
35(a) n=100 sum=0 forcounterinrange(1,n+1): sum=sum+counter print("Sumof1until%d:%d"%(n,sum)) Output: Sumof1until100:5050
[OR]
(b) s1=input("Enterthestringtobereplaced:") s2=input("Enterthestringtoreplacewith") s1=s2 print("Replacedstringis",s1) Output: Enterthestringtobereplaced:Computer Enterthestringtoreplacewith:repcomputer Replacedstringisrepcomputer
36(a) classTr: def__init__(self,a,b,c): self.a=float(a) self.b=float(b) self.c=float(c) defarea(self): s=(self.a+self.b+self.c)/2 return((s*(s-self.a)*(s-self.b)*(s-self.c)**0.5))
ANSWERS G-37
a=input("Enterside1:") b=input("Enterside2:") c=input("Enterside3:") ans=Tr(a,b,c) print(ans.area()) Output: Enterside1:3 Enterside2:4 Enterside3:5 6.0
[OR]
(b) (i) Database Administrator Database Administrator or DBA is the one who manages the complete database
managementsystem.DBAtakescareofthesecurityoftheDBMS,managingthelicensekeys,managinguseraccountsandaccessetc.
(ii) Application Programmers or Software Developers ThisusergroupisinvolvedindevelopinganddesigningthepartsofDBMS. (iii) End User Endusersaretheonewhostore,retrieve,updateanddeletedata. (iv) Database designers:areresponsibleforidentifyingthedatatobestoredinthedatabase
forchoosingappropriatestructurestorepresentandstorethedata. 37(a) TheDatabaseManagementSystemcanbedividedintofivemajorcomponentsasfollows:
(i)Hardware (ii)Software (iii)Data (iv)Procedures/Methods (v)DatabaseAccessLanguages (i) Hardware: The computer, hard disk, I/O
channels for data, and any other physicalcomponentinvolvedinstorageofdata
(ii) Software:Thismain component is a programthat controls everything. The DBMS softwareis capable of understanding the DatabaseAccessLanguagesand interprets intodatabasecommandsforexecution.
(iii) Data: It is that resource for which DBMS isdesigned.DBMScreationistostoreandutilizedata.
(iv) Procedures/Methods: They are generalinstructions to use a database managementsystem such as installation ofDBMS,managedatabases to take backups, report generation,etc.
(v) DataBase Access Languages: They are the languages used to write commands toaccess,insert,updateanddeletedatastoredinanydatabase.
[OR]
Hardware
Data BaseAccessLanguages
DATA
software
USERComponents of DBMS
Procedures/ Methods
G-38 Computer SCienCe – XII
(b) IN Keyword TheINkeywordisusedtospecifyalistofvalueswhichmustbematchedwiththerecord
values.Inotherwordsitisusedtocompareacolumnwithmorethanonevalue.ItissimilartoanORcondition.
Forexample: SELECTAdmno,Name,PlaceFROMStudentWHEREPlaceIN("Chennai","Delhi");
Adm No Name Place100 Ashish Chennai101 Adarsh Delhi103 Ayush Delhi104 Abinandh Chennai105 Revathi Chennai107 Hema Chennai
NOT IN: TheNOTINkeyworddisplaysonlythoserecordsthatdonotmatchinthelist. Forexample: SELECTAdmno,Name,PlaceFROMStudentWHEREPlaceNOTIN("Chennai","Delhi"); willdisplaystudentsonlyfromplacesotherthan"Chennai"and"Delhi".
Adm No Name Place102 Akshith Bangalore106 Devika Bangalore
38(a) Mode Description'r' Openafileforreading.(default)'w' Openafileforwriting.Createsanewfileifitdoesnotexistortruncatesthe
fileifitexists.'x' Openafileforexclusivecreation.Ifthefilealreadyexists,theoperationfails.'a' Openforappendingattheendofthefilewithouttruncatingit.Createsanew
fileifitdoesnotexist.'t' Openintextmode.(default)'b' Openinbinarymode.'+' Openafileforupdating(readingandwriting)
[OR]
(b) Python getopt module ThegetoptmoduleofPythonhelpsyoutoparse(split)command-lineoptionsandarguments. Thismoduleprovidestwofunctionstoenablecommand-lineargumentparsing. getopt.getoptmethod Thismethodparsescommand-lineoptionsandparameterlist.Followingisthesyntaxfor
thismethod-
ANSWERS G-39
<opts>,<args>=getopt.getopt( argv, options, {long_options]) Hereisthedetailoftheparameters-
argv- Thisistheargumentlistofvaluestobeparsed(splited).Inourpro-gramthecompletecommandwillbepassedasalist.
options- ThisisstringofoptionlettersthatthePythonprogramrecognizeas,forinputorforoutput,withoptions(like'i'or'o')thatfollowedbyacolon(:).Herecolonisusedtodenotethemode.
long_options- Thisparameterispassedwithalistofstrings.ArgumentofLongoptionsshouldbefollowedbyanequalsign('=').InourprogramtheC++filenamewillbepassedasstringand'i'alsowillbepassedalongwithtoindicateitastheinputfile.
getopt()methodreturnsvalueconsistingoftwoelements.Eachofthesevaluesarestoredseparatelyintwodifferentlist(arrays)optsandargs.Optscontainslistofsplittedstringslikemode,pathandargscontainsanystringifatallnotsplittedbecauseofwrongpathormode.argswillbeanemptyarrayifthereisnoerrorinsplittingstringsbygetopt().ForexampleThePythoncodewhichisgoingtoexecutetheC++filep4incommandlinewillhavethegetopt()methodlikethefollowingone.
opts,args=getopt.getopt(argv,"i:",['ifile='])
whereoptscontains [('-i','c:\\pyprg\\p4')]–i:- optionnothingbutmodeshouldbefollowedby:'c:\\pyprg\\p4' valuenothingbuttheabsolutepathofC++file.Inourexamplessincetheentirecommandlinecommandsareparsedandnoleftoverargument,thesecondargumentargswillbeempty[].Ifargsisdisplayedusingprint()commanditdisplaystheoutputas[].
>>>print(args) [] SomemorecommandforwrappingC++code if__name__=='__main__’; main(sys.argv[1:]) __name__(ASpecialvariable)inPython Sincethereisnomain()functioninPython,whenthecommandtorunaPythonprogram
isgiventotheinterpreter,thecodethatisatlevel0indentationistobeexecuted.However,beforedoingthat,interpreterwilldefineafewspecialvariables._name_isonesuchspecialvariablewhichbydefaultstoresthenameofthefile.Ifthesourcefileisexecutedasthemainprogram,theinterpretersetsthe_name_variabletohaveavalueas"_main_"
__name__isabuilt-invariablewhichevaluatestothenameofthecurrentmodule.Thusitcanbeusedtocheckwhetherthecurrentscriptisbeingrunonitsown.
G-40 Computer SCienCe – XII
Forexampleconsiderthefollowing if__name__=='__main__': main(sys.argv[1:]) ifthecommandlinePythonprogramitselfisgoingtoexecutefirst,then_main_contains
thenameofthatPythonprogramandthePythonspecialvariable_name_alsocontainthePythonprogramname.IftheconditionistrueitcallsthemainwhichispassedwithC++fileasargument.
Sample Paper-8PART - III
25. InPython,theprint()functionisusedtodisplayresultonthescreen.Thesyntaxforprint()isasfollows:
Example: print("stringtobedisplayedasoutput" ) print(variable) print("Stringtobedisplayedasoutput",variable) print("String1",variable,"String2",variable,"String3"……) 26. AnIdentifierisanameusedtoidentifyavariable,function,class,moduleorobject. • Anidentifiermuststartwithanalphabet(A..Zora..z)orunderscore(_). • Identifiersmaycontaindigits(0..9) • Pythonidentifiersarecasesensitive.i.e.,uppercaseandlowercaselettersaredistinct. • Identifiersmustnotbeapythonkeyword. • Pythondoesnotallowpunctuationcharactersuchas%,$,@etc.,withinidentifiers. 27. Tablesaretheonlywaytostoredata,thereforealltheinformationhastobearrangedinthe
formoftables.TheSQLprovidesapredeterminedsetofcommandstoworkondatabases. Keywords:TheyhaveaspecialmeaninginSQL.Theyareunderstoodasinstructions. Commands:Theyareinstructionsgivenbytheusertothedatabasealsoknownasstatements. Clauses:Theybeginwithakeywordandconsistofkeywordandargument. Arguments:Theyarethevaluesgiventomaketheclausecomplete. 28. Conditional operator
Ternaryoperatorisalsoknownasconditionaloperatorthatevaluatesomethingbasedonaconditionbeingtrueorfalse.Itsimplyallowstestingaconditioninasinglelinereplacingthemultilineif-elsemakingthecodecompact.TheSyntaxconditionaloperatoris, Variable Name = [on_true] if [Test expression] else [on_false] Example : min=50if49<50else70#min=50 min=50if49>50else70#min=70
29. letrecgcdab:= ifb< >0thengcdb(amodb)elsereturna;; output gcd1327;;
ANSWERS G-41
-:int=1 gcd205367826;; -:int=2 Intheaboveexampleprogram'gcd'isthenameofthefunctionwhichrecursivelycalledtill
thevariable'b'becomes'0'.Rememberband(amodb)aretwoargumentspassedto'a'and'b'ofthegcdfunction.
30. SAVEPOINT command TheSAVEPOINTcommandisusedtotemporarilysaveatransactionsothatyoucanrollback
tothepointwheneverrequired.ThedifferentstatesofourtablecanbesavedatanytimeusingdifferentnamesandtherollbacktothatstatecanbedoneusingtheROLLBACKcommand.
SAVEPOINT savepoint_name; UPDATE Student SET Name = 'Mini ' WHERE Admno=105; SAVEPOINT A; 31. Output: Enterastring:welcome Subscript[–1]:e Subscript[–2]:m Subscript[–3]:o Subscript[–4]:c Subscript[–5]:l Subscript[–6]:e Subscript[–7]:w 32. [1,2,4,8,16] 33. Output: Mani 500
PART - IV 34(a) (i) Union:Itincludesallelementsfromtwoormoresets
Inpython,theoperator|isusedtounionoftwosets.Thefunctionunion()isalsousedtojointwosetsinpython.
G-42 Computer SCienCe – XII
(ii) Intersection:Itincludesthecommonelementsintwosets
Theoperator&isusedtointersecttwosetsinpython.Thefunctionintersection()isalsousedtointersecttwosetsinpython.(iii) Difference Itincludesallelementsthatareinfirstset(saysetA)butnotinthesecondset(saysetB)
Theminus(–)operatorisusedtodifferencesetoperationinpython.Thefunctiondifference() isalsousedtodifferenceoperation.(iv) Symmetric differenceItincludesalltheelementsthatareintwosets(saysetsAandB)butnottheonethatarecommontotwosets.
ANSWERS G-43
Thecaret(^)operatorisusedtosymmetricdifferencesetoperationinpython.Thefunctionsymmetric_difference()isalsousedtodothesameoperation.
[OR] (b) Inserting elements in a list
append()functioninPythonisusedtoaddmoreelementsinalist.But,itincludeselementsattheendofalist.Ifyouwanttoincludeanelementatyourdesiredposition,youcanuseinsert()functionisusedtoinsertanelementatanypositionofalist.Syntax: List.insert (position index, element)Example>>>MyList=[34,98,47,'Kannan','Gowrisankar','Lenin','Sreenivasan']>>>print(MyList) [34,98,47,'Kannan','Gowrisankar','Lenin','Sreenivasan']>>>MyList.insert(3,'Ramakrishnan')>>>print(MyList)[34,98,47,'Ramakrishnan','Kannan','Gowrisankar','Lenin','Sreenivasan']Intheaboveexample,insert()functioninsertsanewelement'Ramakrishnan'attheindexvalue3,ie.atthe4thposition.Whileinsertinganewelementinbetweentheexistingelements,ataparticularlocation,theexistingelementsshiftsonepositiontotheright.
35(a) 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5i=1while(i<=6): forjinrange(1,i): print(j,end='\t') print(end='\n') i+=1
[OR]
(b) TheALTERcommandisusedtoalter thetablestructurelikeaddingacolumn,renamingtheexistingcolumn,changethedatatypeofanycolumnorsizeofthecolumnordeletethecolumnfromthetable.Itisusedinthefollowingway:
ALTER TABLE <table-name> ADD <column-name> <data type> <size>; Toaddanewcolumn"Address"oftype'char'totheStudenttable,thecommandisusedas
ALTER TABLE Student ADD Address char; To modify existing column of table, theALTER TABLE command can be used with
MODIFYclauselikewise: ALTER <table-name> MODIFY<column-name> <data type> <size>; ALTER TABLE Student MODIFY Address char (25);
G-44 Computer SCienCe – XII
TheabovecommandwillmodifytheaddresscolumnoftheStudenttabletonowhold25characters.
TheALTERcommandcanbeusedtorenameanexistingcolumninthefollowingway: ALTER <table-name> RENAME old-column-name TO new-column-name; ForexampletorenamethecolumnAddresstoCity,thecommandisusedas: ALTER TABLE Student RENAME Address TO City; TheALTERcommandcanalsobeusedtoremoveacolumnorallcolumns,forexample
toremoveaparticularcolumn,theDROP COLUMNisusedwiththeALTER TABLEtoremoveaparticularfield,thecommandcanbeusedas:
ALTER <table-name> DROP COLUMN <column-name>; ToremovethecolumnCityfromtheStudenttable,thecommandisusedas: ALTER TABLE Student DROP COLUMN City; 36(a) Output: (i) SELECT*FROMemployeeORDERBYDESC; (ii) SELECT * FROM employee WHERE ((allowance >= 5000) AND (allowance
<=7000)); (iii) DELETEFROMemployeeWHEREdesig="Mechanic"; (iv) INSERTINTOemployee(Empcode,Name,desig,pay,allowance)VALUES('M1006',
'RAM','Mechanic',22000,8000); (v) SELECT*FROMemployeeWHEREdesig='operator';
[OR] (b) AsyouknowPythonprovidesaneasywaytoworkwithCSVfileandhascsvmoduletoread
andwritedatainthecsvfile.Intheprevioustopics,YouhavelearnedhowtoreadCSVfilesinPython.Insimilarway,YoucanalsowriteaneworeditanexistingCSVfilesinPython.
(i) CreatingANewNormalCSVFile (ii) ModifyingAnExistingFile (iii) WritingOnACSVFilewithQuotes (iv) WritingOnACSVFilewithCustomDelimiters (v) WritingOnACSVFilewithLineterminator (vi) WritingOnACSVFilewithQuotechars (vii) WritingCSVFileIntoADictionary (viii)GettingDataAtRuntimeAndWritingInaFile 37(a) classSample: def__init__(self,n1,n2): self.n1=n1 self.__n2=n2 defdisplay(self): print("Classvariable1=",self.n1) print("Classvariable2=",self.__n2) S=Sample(12,14) S.display() print("Value1=",S.n1) print("Value2=",S.__n2) Intheaboveprogram,therearetwoclassvariablesn1andn2aredeclared.Thevariablen1
ANSWERS G-45
isapublicvariableandn2isaprivatevariable.Thedisplay()membermethodisdefinedtoshowthevaluespassedtothesetwovariables.
Theprintstatementsdefinedwithinclasswillsuccessfullydisplaythevaluesofn1andn2,eventhoughtheclassvariablen2isprivate.Because,inthiscase,n2iscalledbyamethoddefinedinsidetheclass.But,whenwetrytoaccessthevalueofn2fromoutsidetheclassPythonthrowsanerror.Because,privatevariablecannotbeaccessedfromoutsidetheclass.
Output: Classvariable1=12 Classvariable2=14 Value1=12 Traceback(mostrecentcalllast): File"D:/Python/Class-Test-04.py",line12,in<module> print("Value2=",S.__n2) AttributeError:'Sample'objecthasnoattribute'__n2'
[OR] (b) Asyouknowatupleisimmutable,theelementsinatuplecannotbechanged.Insteadof
alteringvaluesinatuple,joiningtwotuplesordeletingtheentiretupleispossible. Example: #Programtojointwotuples Tup1=(2,4,6,8,10) Tup2=(1,3,5,7,9) Tup3=Tup1+Tup2 print(Tup3) Output: (2,4,6,8,10,1,3,5,7,9) Todeleteanentiretuple,thedelcommandcanbeused. Syntax: del tuple_name Example: Tup1=(2,4,6,8,10) print("TheelementsofTup1is",Tup1) delTup1 print(Tup1) Output: TheelementsofTup1is(2,4,6,8,10) Traceback(mostrecentcalllast): File"D:/Python/TupleExamp1.py",line4,in<module> print(Tup1) NameError:name'Tup1'isnotdefined Notethat,theprintstatementintheabovecodeprintstheelements.Then,thedelstatement
deletestheentiretuple.Whenyoutrytoprintthedeletedtuple,Pythonshowstheerror. 38(a) Whenweneedtoconstructachainofifstatement(s)then'elif'clausecanbeusedinsteadof
'else'. Syntax: if <condition-1>:
G-46 Computer SCienCe – XII
statements-block 1 elif <condition-2>: statements-block 2 else: statements-block n In the syntax of if..elif..else mentioned
above, condition-1 is tested if it is true thenstatements-block1 is executed, otherwisethe control checks condition-2, if it is truestatements-block2 is executed and even if itfailsstatements-blocknmentionedinelsepartisexecuted.
'elif'clausecombinesif..else-if..elsestatementstooneif..elif…else.'elif'canbeconsideredtobeabbreviationof'elseif'.Inan‘if’statementthereisnolimitof'elif'clausethatcanbeused,butan'else'clauseifusedshouldbeplacedattheend.
Example: Program to illustrate the use of nested if statement Average Grade >=80andabove A >=70and<80 B >=60and<70 C >=50and<60 D Otherwise E m1=int(input("Entermarkinfirstsubject:”)) m2=int(input("Entermarkinsecondsubject:")) avg=(m1+m2)/2 ifavg>=80: print("Grade:A") elifavg>=70andavg<80: print("Grade:B") elifavg>=60andavg<70: print("Grade:C") elifavg>=50andavg<60: print("Grade:D") else: print("Grade:E") Output 1: Entermarkinfirstsubject:34 Entermarkinsecondsubject:78 Grade:D
Test Expression
of if
Test Expression
of elifBody of if
Body of elifBody of else
false
false
True
True
if..elif..else statement execution
ANSWERS G-47
Output 2 : Entermarkinfirstsubject:67
[OR]
(b) Parametersorargumentscanbepassedtofunctions def function_name (parameter(s) separated by comma): Letussee theuseofparameterswhiledefiningfunctions.Theparameters thatyouplace
intheparenthesiswillbeusedbythefunctionitself.Youcanpassallsortsofdatatothefunctions.Hereisanexampleprogramthatdefinesafunctionthathelpstopassparametersintothefunction.
#assumew=3andh=5 defarea(w,h): returnw*h print(area(3,5)) The above code assigns the width and height values to the parameters w and h. These
parametersareusedinthecreationofthefunction"area".Whenyoucalltheabovefunction,itreturnstheproductofwidthandheightasoutput.
Thevalueof3and5arepassedtowandhrespectively,thefunctionwillreturn15asoutput.
Sample Paper-9PART - III
25. InPython,aclass isdefinedbyusing thekeywordclass.Everyclasshasauniquenamefollowedbyacolon(:).
Syntax: class class_name: statement_1 statement_2 ………….. ………….. statement_n Where,statementinaclassdefinitionmaybeavariabledeclaration,decisioncontrol,loop
orevenafunctiondefinition.Variablesdefinedinsideaclassarecalledas"ClassVariable"andfunctionsarecalledas"Methods".Classvariableandmethodsaretogetherknownasmembersoftheclass.Theclassmembersshouldbeaccessedthroughobjectsorinstanceofclass.AclasscanbedefinedanywhereinaPythonprogram.
Example:Programtodefineaclass classSample: x,y=10,20 # class variables Intheabovecode,nameoftheclassisSampleandithastwovariablesxandyhavingthe
initialvalue10and20respectively.Toaccessthevaluesdefinedinsidetheclass,youneedanobjectorinstanceoftheclass.
G-48 Computer SCienCe – XII
26. ThebasicrulesforglobalkeywordinPythonare:•Whenwedefineavariableoutsideafunction,it’sglobalbydefault.Youdon’thavetouseglobalkeyword.
•Weuseglobalkeywordtoreadandwriteaglobalvariableinsideafunction.•Useofglobalkeywordoutsideafunctionhasnoeffect.
27. SAVEPOINT command TheSAVEPOINTcommandisusedtotemporarilysaveatransactionsothatyoucanrollback
tothepointwheneverrequired.ThedifferentstatesofourtablecanbesavedatanytimeusingdifferentnamesandtherollbacktothatstatecanbedoneusingtheROLLBACKcommand.
SAVEPOINT savepoint_name; UPDATE Student SET Name = 'Mini ' WHERE Admno=105; SAVEPOINT A; 28. Example: importsqlite3 connection=sqlite3.connect("Academy.db") cursor=connection.cursor() cursor.execute("SELECTgender,count(gender)FROMstudentGroupBYgender") result=cursor.fetchall() print(*result,sep="\n") Output: ('F',2) ('M',5) 29. Output: weoo130.
( ) [ ] { }, : . ' = ;
+= –= *= /= //= %=&= |= ^= >>= <<= **=
31. InPythonastringliteralisasequenceofcharacterssurroundedbyquotes.Pythonsupportssingle,doubleandtriplequotesforastring.Acharacterliteralisasinglecharactersurroundedbysingleordoublequotes.Thevaluewithtriple-quote"' '"isusedtogivemulti-linestringliteral.
strings="ThisisPython" char="C" multiline_str="'Thisisamultilinestringwithmorethanonelinecode."' 32. #Programtodemonstrateconditionaloperator a,b=30,20 #Copyvalueofainminifa<belsecopyb min=aifa<belseb print("TheMinimumofAandBis",min)
ANSWERS G-49
#EndoftheProgram Output: TheMinimumofAandBis2033. •Functionblocksbeginwiththekeyword"def"followedbyfunctionnameand
parenthesis().•Anyinputparametersorargumentsshouldbeplacedwithintheseparentheseswhenyoudefineafunction.•Thecodeblockalwayscomesafteracolon(:)andisindented.•Thestatement"return[expression]"exitsafunction,optionallypassingbackanexpressiontothecaller.A"return"withnoargumentsisthesameasreturnNone.
PART - IV 34(a)
Question AnswerTo test Logical Operators:Example - Code Output#Demo Program to test Logical Operatorsa=int (input("Enter a Value for A:"))b=int (input("Enter a Value for B:"))print ("A = ",a, " and b = ",b)print ("The a > b or a == b = ",a>b or a==b)print ("The a > b or a == b = ",a>b and a==b)print ("The not a > b ",not a>b)#Program End
EnteraValueforA:50EnteraValueforB:40A=50andb=40Thea>bora==b=TrueThea>banda==b=FalseThenota>b=False
[OR]
(b) Example: #Program to check if the accepted number odd or even a=int(input("Enteranynumber:")) ifa%2==0: print(a,"isanevennumber") else: print(a,"isanoddnumber") Output 1: Enteranynumber:56 56isanevennumber Output 2: Enteranynumber:67 67isanoddnumber 35(a) Syntax: while <condition>: statements block 1
G-50 Computer SCienCe – XII
[else: statements block 2] Inthewhileloop,theconditionisanyvalidBoolean
expression returning True or False. The else partofwhile isoptionalpartofwhile.The statementsblock1 is kept executed till the condition isTrue.If theelsepart iswritten, it is executedwhen theconditionistestedFalse.Recallwhileloopbelongstoentrychecklooptype, that is it isnotexecutedeven once if the condition is tested False in thebeginning.
Example: program to illustrate the use of while loop - to print all numbers from 10 to 15 i=10 #initializing part of the control variable while(i<=15): # test condition print(i,end='\t') # statements - block 1 i=i+1 # Updation of the control variable Output: 101112131415
[OR]
(b) Types of FunctionsBasically,wecandividefunctionsintothefollowingtypes: (i) User-definedFunctions (ii) Built-inFunctions (iii) LambdaFunctions (iv) RecursionFunctions
Functions DescriptionUser-definedfunctions Functionsdefinedbytheusersthemselves.Built-infunctions FunctionsthatareinbuiltwithinPython.Lambdafunctions Functionsthatareanonymousun-namedfunction.Recursionfunctions Functionsthatcallsitselfisknownasrecursive.
(i) Syntax for User defined function def <function_name ([parameter1, parameter2…] )> : <Block of Statements> return <expression / None>Example: defhello(): print("hello-Python") return
Condition
Conditional Code
while Expression: Statement (s)
if conditions is true
if condition is false
ANSWERS G-51
Advantages of User-defined Functions: (i)Functionshelpustodivideaprogramintomodules.Thismakesthecodeeasiertomanage. (ii)Itimplementscodereuse.Everytimeyouneedtoexecuteasequenceofstatements,all
youneedtodoistocallthefunction.(iii)Functions,allowsustochangefunctionalityeasily,anddifferentprogrammerscanwork
ondifferentfunctions.(ii) Anonymous FunctionsInPython,anonymousfunctionisafunctionthatisdefinedwithoutaname.Whilenormalfunctionsaredefinedusing thedef keyword, inPythonanonymousfunctionsaredefinedusingthelambdakeyword.Hence,anonymousfunctionsarealsocalledaslambda functions.The use of lambda or anonymous function:•Lambdafunctionismostlyusedforcreatingsmallandone-timeanonymousfunction.•Lambdafunctionsaremainlyusedincombinationwiththefunctionslikefilter(),map()andreduce().
Syntax of Anonymous FunctionsThesyntaxforanonymousfunctionsisasfollows: lambda [argument(s)] :expressionExample: sum=lambdaarg1,arg2:arg1+arg2 print('TheSumis:',sum(30,40)) print('TheSumis:',sum(-30,40))Output: TheSumis:70 TheSumis:10Theabovelambdafunctionthataddsargumentarg1withargumentarg2andstorestheresultinthevariablesum.Theresultisdisplayedusingtheprint().(iii) Functions using librariesBuilt-in and Mathematical functions
Function Description Syntax Exampleabs() Returnsanabsolutevalueof
anumber.The argument may be aninteger or a floating pointnumber.
abs(x)
x=20y=-23.2print('x=',abs(x))print('y=',abs(y))Output: x=20 y=23.2
G-52 Computer SCienCe – XII
ord() Returns theASCII value forthegivenUnicodecharacter.This function is inverse ofchr()function. ord(c)
c='a'd='A'print('c=',ord(c))print('A=',ord(d))Output: c = 97 A = 65
(iv) Recursive functionsWhenafunctioncallsitselfisknownasrecursion.Recursionworkslikeloopbutsometimesitmakesmoresensetouserecursionthanloop.Youcanconvertanylooptorecursion.Example: deffact(n): ifn==0: return1 else: returnn*fact(n-1) print(fact(0)) print(fact(5)) Output: 1 120
36(a) (i)Therange()isafunctionusedtogenerateaseriesofvaluesinPython.Usingrange()function,youcancreatelistwithseriesofvalues.Therange()functionhasthreearguments.
Syntax of range ( ) function: range (start value, end value, step value)where,•start value – beginningvalueofseries.Zeroisthedefaultbeginningvalue.•end value – upperlimitofseries.Pythontakestheendingvalueasupperlimit–1.•step value – Itisanoptionalargument,whichisusedtogeneratedifferentintervalofvalues.Example : Generating whole numbers upto 10forxinrange(1,11): print(x)Output 1 2 3 4 5 6 7
ANSWERS G-53
8 9 10
(ii) Creating a list with series of valuesUsingtherange()function,youcancreatealistwithseriesofvalues.Toconverttheresultofrange()functionintolist,weneedonemorefunctioncalledlist().Thelist()functionmakestheresultofrange()asalist.Syntax: List_Varibale = list ( range ( ) )NoteThelist()functionisallsousedtocreatelistinpython.Example>>>Even_List=list(range(2,11,2))>>>print(Even_List)[2,4,6,8,10]Intheabovecode,list()functiontakestheresultofrange()asEven_Listelements.Thus,Even_Listlisthastheelementsoffirstfiveevennumbers.
(iii)Wecancreateanyseriesofvaluesusingrange()function.Thefollowingexampleexplainshowtocreatealistwithsquaresoffirst10naturalnumbers.
Example : Generating squares of first 10 natural numberssquares=[]forxinrange(1,11): s=x**2 squares.append(s) print(squares)Output [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[OR] (b) print("Enter'x'forexit.") string1=input("Enterfirststring:") ifstring1=='x': exit(); else: string2=input("Entersecondstring:") print("\nBothstringsbeforeswap:") print("Firststring=",string1) print("Secondstring=",string2) temp=string1 string1=string2 string2=temp print("\nBothstringsafterswap:") print("Firststring=",string1)
G-54 Computer SCienCe – XII
print("Secondstring=",string2) Output: Enter'x'forexit Enterfirststring:code Entersecondstring:python Bothstringsbeforeswap: Firststring=code Secondstring=python Bothstringsafterswap: Firststring=python Secondstring=code 37(a) num=[] forxinrange(1,21): num.append(x) print("Thelistofnumbersfrom1to20=",num) forindex,iinenumerate(num): if(i%3==0) delnum[index] print("Thelistafterdeletingnumbers",num) Output: Thelistofnumbersfrom1to20=[1,2,3,4...20] Thelistafterdeletingnumbers[1,2,4,5,7,8,10,11,13,14,16,17,19,20]
[OR] (b) classstud: def__init__(self): self.name="" self.m1=0 self.m2=0 self.tot=0 defgdata(self): self.name=input("Enteryourname") self.m1 =int(input("Entermarks1")) self.m2 =int(input("Entermarks2")) self.tot =self.m1+self.m2 defdisp(self): print(self.name) print(self.m1) print(self.m2) print(self.tot) mlist=[] st=stud() st.gdata()
ANSWERS G-55
mlist.append(st) forxinmlist: x.disp() Output: Enteryourname Ram Entermarks1 100 Entermarks2 100 Ram100100 200 38(a) Constraintsensuredatabaseintegrity,thereforeknownasdatabaseintegrityconstraints.
Constraint
Unique Constraint
Primary Key Constraint
Default Constraint
Check Constraint
(i) Unique Constraint Thisconstraintensuresthatnotworowshavethesamevalueinthespecifiedcolumns.For
exampleUNIQUEconstraintappliedonAdmnoofstudenttableensuresthatnotwostudentshavethesameadmissionnumberandtheconstraintcanbeusedas:
CREATETABLEStudent ( Admno integer NOT NULL UNIQUE, → Unique constraint Name char (20) NOT NULL, Gender char (1), Age integer, Place char (10), ); TheUNIQUEconstraintcanbeappliedonlytofieldsthathavealsobeendeclaredasNOT
NULL. Whentwoconstraintsareappliedonasinglefield,itisknownasmultipleconstraints.Inthe
aboveMultipleconstraintsNOTNULLandUNIQUEareappliedonasinglefieldAdmno,theconstraintsareseparatedbyaspaceandattheendofthefielddefinitionacomma(,)isadded.ByaddingthesetwoconstraintsthefieldAdmnomusttakesomevaluei.e.willnotbeNULLandshouldnotbeduplicated.
(ii) Primary Key Constraint ThisconstraintdeclaresafieldasaPrimarykeywhichhelpstouniquelyidentifyarecord.It
issimilartouniqueconstraintexceptthatonlyonefieldofatablecanbesetasprimarykey.TheprimarykeydoesnotallowNULLvaluesandthereforeafielddeclaredasprimarykeymusthavetheNOT NULLconstraint.
ExampleshowingPrimaryKeyConstraintinthestudenttable: CREATE TABLE Student (
G-56 Computer SCienCe – XII
Admno integer NOT NULL PRIMARY KEY, → Primary Key constraint Name char(20)NOT NULL, Gender char(1), Age integer, Place char(10), ); IntheaboveexampletheAdmnofieldhasbeensetasprimarykeyandthereforewillhelp
ustouniquelyidentifyarecord,itisalsosetNOT NULL,thereforethisfieldvaluecannotbeempty.
(iii) DEFAULT Constraint TheDEFAULTconstraintisusedtoassignadefaultvalueforthefield.Whennovalueis
givenforthespecifiedfieldhavingDEFAULTconstraint,automaticallythedefaultvaluewillbeassignedtothefield.
ExampleshowingDEFAULTConstraintinthestudenttable: CREATE TABLE Student ( Admno integer NOT NULL PRIMARY KEY, Name char(20) NOT NULL, Gender char(1), Age integer DEFAULT = "17", → Default Constraint Place char(10), ); Intheaboveexamplethe"Age"fieldisassignedadefaultvalueof17,thereforewhenno
valueisenteredinagebytheuser,itautomaticallyassigns17toAge. (iv) Check Constraint Thisconstrainthelpstosetalimitvalueplacedforafield.Whenwedefineacheckconstraint
onasinglecolumn,itallowsonlytherestrictedvaluesonthatfield. Exampleshowingcheckconstraintinthestudenttable: ( Admno integer NOT NULL PRIMARY KEY Name char(20)NOT NULL, Gender char(1), Age integer (CHECK<=19), → Check Constraint Place char(10), ); IntheaboveexamplethecheckconstraintissettoAgefieldwherethevalueofAgemustbe
lessthanorequalto19. Note: Thecheckconstraintmayuserelationalandlogicaloperatorsforcondition. (v) TABLE CONSTRAINT Whentheconstraintisappliedtoagroupoffieldsofthetable,itisknownasTableconstraint.
ANSWERS G-57
Thetableconstraintisnormallygivenattheendofthetabledefinition.LetustakeanewtablenamelyStudent1withthefollowingfieldsAdmno,Firstname,Lastname,Gender,Age,Place:
CREATE TABLE Student 1 ( Admno integer NOT NULL, Firstname char(20), Lastname char(20), Gender char(1), Age integer, Place char(10), PRIMARY KEY (Firstname, Lastname) → Table constraint ); Intheaboveexample,thetwofields,FirstnameandLastnamearedefinedasPrimarykey
whichisaTableconstraint.
[OR]
(b) importcsvrow=['3','Meena','Bangalore']withopen('student.csv','r')asreadFile:reader=csv.reader(readFile)lines=list(reader) # list()- to store each row of data as a listlines[3]=rowwithopen('student.csv','w')aswriteFile:# returns the writer object which converts the user data with delimiterwriter=csv.writer(writeFile)#writerows()method writes multiple rows to a csv filewriter.writerows(lines)readFile.close()writeFile.close()Whenweopenthestudent.csvfilewithtexteditor,thenitwillshow:
Roll No Name City1 Harshini, Chennai2 Adhith, Mumbai3 Meena, Bengaluru4 egiste, Tiruchy5 Venkat, Madurai
G-58 Computer SCienCe – XII
Sample Paper-10PART - III
25. welcome–modulename.–dotoperator
display()–functionname 26. (i)ChooseRun→RunModuleorPressF5
(ii) Ifyourcodehasanyerror,itwillbeshowninredcolorintheIDLEwindow,andPythondescribesthetypeoferroroccurred.Tocorrecttheerrors,gobacktoScripteditor,makecorrections,savethefileusingCtrl+SorFile→Saveandexecuteitagain.
(iii)Forallerrorfreecode,theoutputwillappearintheIDLEwindowofPython. 27. •SQLiteisasimplerelationaldatabasesystem,whichsavesitsdatainregulardatafilesor
evenintheinternalmemoryofthecomputer.•Itisdesignedtobeembeddedinapplications,insteadofusingaseparatedatabaseserver programsuchasMySQLorOracle.•SQLiteisfast,rigorouslytested,andflexible,makingiteasiertowork.Pythonhasanative libraryforSQLite.
28. Displaying A record using fetchone()Thefetchone()methodreturnsthenextrowofaqueryresultsetorNoneincasethereisnorowleft.Exampleimportsqlite3connection=sqlite3.connect("Academy.db")cursor=connection.cursor()cursor.execute("SELECT*FROMstudent")print("\nfetchone:")res=cursor.fetchone()print(res)
ANSWERS G-59
OUTPUT fetchone: (1,'Akshay','B','M',87.8,'2001-12-12')Displayingusing fetchmany()Displayingspecifiednumberofrecordsisdonebyusingfetchmany().Thismethodreturnsthenextnumberofrows(n)oftheresultset.Example : Program to display the content of tuples using fetchmany()importsqlite3connection=sqlite3.connect("Academy.db")cursor=connection.cursor()cursor.execute("SELECT*FROMstudent")print("fetchingfirst3records:")result=cursor.fetchmany(3)print(result)OUTPUTfetchingfirst3records:[(1,'Akshay','B','M',87.8,'2001-12-12'),(2,'Aravind','A','M',92.5,'2000-08-17'),(3,'BASKAR','C','M',75.2,'1998-05-17')]
29. ClassesandObjectsarethekeyfeaturesofObjectOrientedProgramming.ClassisthemainbuildingblockinPython.Objectisacollectionofdataandfunctionthatactonthosedata.Classisatemplatefortheobject.AccordingtotheconceptofObjectOrientedProgramming,objectsarealsocalledasinstancesofaclassorclassvariable.
30. (i)Theelementsofalistarechangeable(mutable)whereastheelementsofatupleare unchangeable(immutable),thisisthekeydifferencebetweentuplesandlist. (ii)Theelementsofalistareenclosedwithinsquarebrackets.But,theelementsofatuple
areenclosedbyparanthesis. (iii)Iteratingtuplesisfasterthanlist. 31. A set is created by placing all the elements separated by commawithin a pair of curly
brackets. Theset()functioncanalsousedtocreatesetsinPython. Syntax: Set_Variable={E1,E2,E3……..En} Example >>>S1={1,2,3,'A',3.14} >>>print(S1) {1,2,3,3.14,'A'} >>>S2={1,2,2,'A',3.14} >>>print(S2) {1,2,'A',3.14}
G-60 Computer SCienCe – XII
32. Program to create a list of numbers from 1 to 20 that are divisible by 4 divBy4=[] foriinrange(21): if(i%4==0): divBy4.append(i) print(divBy4) Output: [0,4,8,12,16,20] 33. Constructorofclasssample... Thevalueis:10
PART - IV 34(a) InPython,aclass isdefinedbyusing thekeywordclass.Everyclasshasauniquename
followedbyacolon(:).Syntax: class class_name: statement_1 statement_2 ………….. ………….. statement_nWhere,statementinaclassdefinitionmaybeavariabledeclaration,decisioncontrol,looporevenafunctiondefinition.Variablesdefinedinsideaclassarecalledas"ClassVariable"andfunctionsarecalledas"Methods".Classvariableandmethodsaretogetherknownasmembersoftheclass.Theclassmembersshouldbeaccessedthroughobjectsorinstanceofclass.AclasscanbedefinedanywhereinaPythonprogram.Example:Programtodefineaclass classSample: x,y=10,20 # class variablesIntheabovecode,nameoftheclassisSampleandithastwovariablesxandyhavingtheinitialvalue10and20respectively.Toaccessthevaluesdefinedinsidetheclass,youneedanobjectorinstanceoftheclass.
[OR] (b) (i) Union: Itincludesallelementsfromtwoormoresets. Inpython,theoperator|isusedtounionoftwosets.Thefunctionunion()isalsousedtojoin
twosetsinpython. Example:ProgramtoJoin(Union)twosetsusingunionoperator set_A={2,4,6,8} set_B={'A','B','C','D'} U_set=set_A|set_B print(U_set)
Set A Set B
ANSWERS G-61
Output: {2,4,6,8,'A','D','C','B'} (ii) Intersection:Itincludesthecommonelementsintwosets Theoperator&isusedtointersecttwosetsinpython.Thefunctionintersection()isalso
usedtointersecttwosetsinpython. Example:Programtoinsecttwosetsusingintersectionoperator set_A={'A',2,4,'D'} set_B={'A','B','C','D'} print(set_A & set_B) Output: {'A','D'}
(iii) Difference:Itincludesallelementsthatareinfirstset(saysetA)butnotinthesecondset(saysetB)
Theminus(-)operatorisusedtodifferencesetoperationinpython. Thefunctiondifference()isalsousedtodifferenceoperation. Example:Programtodifferenceoftwosetsusingminusoperator set_A={'A',2,4,'D'} set_B={'A','B','C','D'} print(set_A - set_B) Output: {2,4}
(iv) Symmetric difference:Itincludesalltheelementsthatareintwosets(saysetsAandB)butnottheonethatarecommontotwosets.
Thecaret(^)operatorisusedtosymmetricdifferencesetoperationinpython.Thefunctionsymmetric_difference()isalsousedtodothesameoperation.
Example:Programtosymmetricdifferenceoftwosetsusingcaretoperator set_A={'A',2,4,'D'} set_B={'A','B','C','D'} print(set_A ^ set_B) Output: {2,4,'B','C'}
35(a) marks=[] subjects=['Tamil','English','Physics','Chemistry','Comp.Science','Maths'] foriinrange(6): m=int(input("EnterMark=")) marks.append(m) forjinrange(len(marks)): print("{}.{}Mark={}".format(j1+,subjects[j],marks[j])) print("TotalMarks=",sum(marks)) Output EnterMark=45
Set A Set B
Set A Set B
Set A Set B
G-62 Computer SCienCe – XII
EnterMark=98 EnterMark=76 EnterMark=28 EnterMark=46 EnterMark=15 1.TamilMark=45 2.EnglishMark=98 3.PhysicsMark=76 4.ChemistryMark=28 5.Comp.ScienceMark=46 6.MathsMark=15 TotalMarks=308
[OR]
(b) classSample: def__init__(self,n1,n2): self.__n1=n1 self.__n2=n2 defdisplay(self): print("classvariable1:",self.__n1) print("classvariable2:",self.__n2) print("sum:",self.__n1+self.__n2) s=sample(10,20) s.display() Output: classvariable1:10 classvariable2:20 sum:30
36(a) CharacteristicsofDatabaseManagementSystem.
1. DatastoredintoTables
Dataisneverdirectlystoredintothedatabase.Dataisstoredintotables,createdinsidethedatabase.DBMSalsoallowstohave relationshipbetween tableswhichmakes thedatamoremeaningfulandconnected.
2. ReducedRedundancy
Inthemodernworldharddrivesareverycheap,butearlierwhenharddrivesweretooexpensive,unnecessaryrepetitionofdataindatabasewasabigproblemButDBMSfollowsNormalisation which divides the data in such a way thatrepetitionisminimum.
ANSWERS G-63
3. DataConsistencyOnlivedata,itisbeingcontinuouslyupdatedandadded,maintainingtheconsistencyofdatacanbecomeachallenge.ButDBMShandlesitbyitself.
4.SupportMultipleuserandConcurrentAccess
DBMSallowsmultipleuserstoworkonit(update,insert,deletedata)atthesametimeandstillmanagestomaintainthedataconsistency.
5. QueryLanguageDBMSprovidesuserswithasimplequerylanguage,usingwhichdatacanbeeasilyfetched,inserted,deletedandupdatedinadatabase.
6. Security
TheDBMSalsotakescareofthesecurityofdata,protectingthedatafromunauthorizedaccess.InatypicalDBMS,wecancreateuseraccountswithdifferentaccesspermissions,usingwhichwecaneasilysecureourdatabyrestrictinguseraccess.
7. DBMSSupportsTransactions
It allowsus tobetterhandleandmanagedata integrity inrealworldapplicationswheremulti-threadingisextensivelyused.
[OR]
(b) (a) CREATE TABLE Command YoucancreateatablebyusingtheCREATETABLEcommand. CREATETABLEStudent (Admnointeger, Namechar(20),\ Genderchar(1), Ageinteger, Placechar(10), ); (b) ALTER COMMAND TheALTERcommandisusedtoalterthetablestructurelikeaddingacolumn,renaming
theexistingcolumn,changethedatatypeofanycolumnorsizeofthecolumnordeletethecolumnfromthetable.
AltertableStudentaddaddresschar; (c) DROP TABLE: Droptablecommandisusedtoremoveatablefromthedatabase. DROPTABLEStudent; 37(a) (i)Itshouldidentifythetypeofdatadivisionsuchasdataitem,segment,recordanddatabasefile. (ii) Itgivesauniquenametoeachdataitemtype,recordtype,filetypeanddatabase. (iii)Itshouldspecifytheproperdatatype. (iv) Itshoulddefinethesizeofthedataitem.
G-64 Computer SCienCe – XII
(v) Itmaydefinetherangeofvaluesthatadataitemmayuse. (vi) Itmayspecifyprivacylocksforpreventingunauthorizeddataentry.
[OR]
(b) Read a CSV File Using Python TherearetwowaystoreadaCSVfile. (i) Usethecsvmodule’sreaderfunction (ii) UsetheDictReaderclass.
TwowaysofReadingCSVFile
reader()function DictReaderclassWays to read CSV file
(i) CSV Module’s Reader Function You can read the contents ofCSVfilewith the help of csv.reader()method.The reader
functionisdesignedtotakeeachlineofthefileandmakealistofallcolumns.Then,youjustchoosethecolumnyouwantthevariabledatafor.Usingthismethodonecanreaddatafromcsvfilesofdifferentformatslikequotes(""),pipe(|)andcomma(,).
The syntax for csv.reader() is csv.reader(fileobject,delimiter,fmtparams) where fileobject:- passesthepathandthemodeofthefile delimiter:- anoptionalparametercontainingthestandarddilectslike,Ietccanbeomitted fmtparams:- optionalparameterwhichhelptooverridethedefaultvaluesofthedialects
likeskipinitialspace,quotingetc.Canbeomitted
CSV file - data with default delimiter comma (,)
CSV file - data with Space at the beginning
CSV file - data with quotes
CSV file - data with customer Delimiters
(ii) Reading CSV File Into A Dictionary ToreadaCSVfileintoadictionarycanbedonebyusingDictReaderclassofcsvmodule
whichworkssimilartothereader()classbutcreatesanobjectwhichmapsdatatoadictionary.Thekeysaregivenbythefieldnamesasparameter.DictReaderworksbyreadingthefirstlineoftheCSVandusingeachcommaseparatedvalueinthislineasadictionarykey.Thecolumnsineachsubsequentrowthenbehavelikedictionaryvaluesandcanbeaccessedwiththeappropriatekey(i.e.fieldname).
ANSWERS G-65
IfthefirstrowofyourCSVdoesnotcontainyourcolumnnames,youcanpassafieldnamesparameter into theDictReader’s constructor to assign the dictionary keysmanually.Themaindifferencebetween the csv.reader() andDictReader() is in simple termscsv. readerand csv.writer work with list/tuple, while csv.DictReader and csv.DictWriter work withdictionary.csv.DictReaderandcsv.DictWritertakeadditionalargumentfieldnamesthatareusedasdictionarykeys.
38(a) Read A CSV File And Store It In A List InthistopicyouaregoingtoreadaCSVfileandthecontentsofthefilewillbestoredasa
list.ThesyntaxforstoringintheListis list=[] #Startastheemptylist list.append(element) #Useappend()toaddelements Forexampleall therowvaluesof"sample.csv"fileisstoredina listusingthefollowing
program importcsv #otherwayofdeclaringthefilename inFile='c:\\pyprg\\sample.csv' F=open(inFile,'r') reader=csv.reader(F) #declaringarray arrayValue=[] #displayingthecontentofthelist forrowinreader: arrayValue.append(row) print(row) F.close()
A1 V
1 Topic 3Topic 2Topic 1A B C
2 threetwoOne3 Example 3Example 2Example 14
fx
Sample5.cv File with selected col
OUTPT[`Topic1`, `Topic2`, `Topic3`][`one`, `two`, `three`][`Example1`, `Example2`, `Example3`]
Topic 1
[OR]
top related