Project Report Aryan Batra 19 Sep
Project Report Aryan Batra 19 Sep
ON
P R O G R A M M IN G W IT H P Y T H O N
B A C H EL O R O F T EC H N O L O G Y
IN
C O M P U T ER SC IEN C E EN G IN EER IN G
Submitted by
A ryanB atra
( 1 3 / 2 3 )
U nderth e guidance of
DEC L A R A T IO N
I h ereby decl
are th at th e M O O C R eport entitl
ed “ PR O G R A M M IN G W IT H
PY T H O N ” is an auth entic record ofmy own carried outas requirementfor th e
award of degree of B T EC H ( C SE) of M ah ant B ach ittar Singh C ol
lege of
Engineering& T ech nol
ogy, Jammu.
M s. K iranpalK our
A C K N O W L EDG EM EN T
I woul
d al
so l
ike to incl
ude specialth anks ofgratitude to Internsh al
a and th eir
course instructorM r. A nujK al
bal
iaforth eirqual
ity ofcourse del
ivering.
DA T E: A ryanB atra
R ol
lN o: 1 3 / 2 3
III
A B S T R A C T
foundationforl
anguage'ssyntax, h istoricalcontext, and th e distinctionsbetweenPyth on2 . xand
variabl
esand data types, gainingasol
id understandingofworkingwith numbers, strings, l
ists,
tupl
es and dictionaries - th e buil
ding bl
ocks for constructing more compl
ex programs.
cl
asses, creatingobjects, impl
ementinginh eritance, and customiz ingobjectbeh aviorth rough th e
rel
ationaldatabases, specifical
ly SQ L ite.
C O N T E N T S
DEC L A R A T IO N I
A C K N O W L EDG EM EN T II
A B ST R A C T III
L IST O F T A B L ES IV
L IST O F F IG U R ES V
C H A P T ER 1 1 IN T R O DU C T IO N T O P Y T H O N 1 -1 0
1.1. Introduction 1
1.2. Pyth onInterpreter 1 - 2
1.2.1. W h atare Intrepreters 1
1.2.2. H ow IntrepretersfunctioninPyth on 2
1.3. Pyth onV ersions 3 - 4
1.3.1. Pyth on2 x 3
1.3.2. Pyth on3 x 4
1.3.3. Difference inPyth on2 xand 3 x 4
1.4. Pyth onF eatures 4 - 6
1.5. B asicSyntaxInPyth on 6 - 1 0
1.5.1. Pyth onIdentifiers 6
1.5.2. Pyth onL inesand Indentation 8
1.5.3. Pyth onM ul ti L inesStatements 9
1.5.4. Pyth onQ uotations 9
1.5.5. Pyth onM ul ti Statements 1 0
C H A P T ER 2 2. U SIN G V A R IA B L ES IN P Y T H O N 1 0 - 2 4
2.1. Introduction 1 0
2.2. W h atare Pyth onDataT ypes 1 1
2.3. N umericDataT ypes 1 3
2.4. Sequence DataT ypes 1 4 - 2 4
2.4.1. StringDataT ype 1 4
2.4.2. L istDataT ype 1 6
2.4.3. T uple DataT ype 1 8
2.4.4. B ooleanDataT ype 2 0
2.4.5. SetDataT ype
2.4.6. Dictionary DataT ype 2 2
2 4
C H A P T ER 3 3. B A SIC P R O G R A M M IN G IN P Y T H O N 2 5 - 3 1
3.1. Introduction 2 5
3.2. C ondtitionalStatements 2 6 - 2 8
3.2.1. Ifstatement 2 6
3.2.2. Ifel se statement 2 6
3.2.3. N ested Ifel se statement 2 7
3.2.4. If- el
if- else statement 2 7
3.2.5. T ernary C onditionalstatement 2 8
3.3. L oopStatements 2 8 - 2 9
3.3.1. W h ilel oop 2 8
3.3.2. F orl oop 2 9
3.4. U singF unctions 3 0 - 3 1
3.4.1. C reatingafunction 3 0
3.4.2. C al l
ingafunction 3 1
C H A P T ER 4 4. O B JEC T O R IEN T ED P R O G R A M M IN G 3 2 - 3 9
U SIN G P Y T H O N
4.1. Introduction 3 2
4.2. Pyth onC lass 3 3
4.3. Pyth onO bjects 3 3
4.4. Pyth onself 3 5
4.5. Pyth on__init__ 3 5
4.6. Pyth onInh eritance 3 7
4.7. Pyth onPol ymorph ism 3 8
4.8. Pyth onEncapsul ation 3 9
C H A P T ER 5 5. C O N N EC T IN G TO SQ L IT E 4 0 - 4 5
DA T A B A SE 4 0
5.1. Introduction 4 1
5.2. C onnectingto SQ L ite 4 3
5.3. SQ L ite Database 4 3
5.3.1. A dvantagesofSQ L ite 4 5
5.3.2. SQ L ite C ommands
A SSIG N M EN T 4 6 -5 8
B IB L O G R A P H Y 5 9
IV
L IS T O F T A B L ES
S. N O TA BL EN O TA BL EN A M E PA G EN O
2 . 2 .1 N umericDataT ypesExampl
es 1 3
V
L IS T O F F IG U R ES
TA BL E
S. N O N O TA BL EN A M E PA G E N O
3 . 4 .1 Pyth onEncapsul
ation 3 9
4 . 5 .1 SQ L ite C onnectionInPyth on 4 2
h ttps: / / www. geeksforgeeks. org/ wh at- is- pyth on- interpreter/
C H A P T ER - 1
IN T R O DU C T IO N T O P Y T H O N P R O G R A M M IN G
1 . 1 IN T R O DU C T IO N
Pyth onisawidel
y used general
- purpose, h igh - l
evelprogrammingl
anguage. Itwascreated by G uido
vanR ossum in1 9 9 1 and furth erdevel
oped by th e Pyth onSoftware F oundation. Itwasdesigned with
anemph asisoncode readabil
ity, and itssyntaxal
lowsprogrammersto expressth eirconceptsin
fewerl
inesofcode. Pyth onisaprogrammingl
anguage th atl
etsyouwork quickl
y and integrate
y. T h ere are two majorPyth onversions: P yth on 2 and P yth on 3 . B oth are
systemsmore efficientl
quite different.
1 . 2 P Y T H O N IN T ER P R ET ER
Itisaninterpreted l
anguage because itexecutesl
ine- by- l
ine instructions. T h ere are actual
ly two way
to execute pyth oncode one isinInteractive mode and anoth erth ingish avingPyth onpromptswh ich
isal
so cal
led scriptmode. Pyth ondoesnotconverth igh l
evelcode into l
ow l
evelcode asmany oth er
programmingl
anguagesdo rath eritwil
lscanth e entire code into someth ingcal
led bytecode. every
time wh enPyth ondevel
operrunsth e code and startto execute th e compil
ationpartexecute firstand
th enitgenerate anbyte code wh ich getconverted by PV M Pyth onV irtualmach ine th atunderstand
th e anal
ogy and give th e desired output.
1 . 2 . 1 W h atare Interpreters?
DEPA R T M EN T O F C SE, M B SC ET 1
PR O G R A M M IN G W IT H PY T H O N
iscal
led Interpretation. F orexampl
e Pyth onisaninterpreted l
anguage, PH P, R uby, and
JavaScript.
1 . 3 P Y T H O N V ER SIO N S
1 . 3 . 1 P yth on2
1 . 3 . 2 P yth on3
R el
eased inth e year2 0 0 8 , Pyth on3 wasnotjustanoth erversionofPyth on2 after
debugging. T h e introductionofPyth onwasmostl
y surrounded by th e motive th atredundancy –
writingrepetitive code orwritingth e same piece ofcode againand again– sh oul
d be removed
from coding. Pyth on3 isbackwardsincompatibl
e and aimsatel
iminatingth e probl
emswh ich
new programmersface wh il
elearningaprogrammingl
anguage.
1 . Y earofR el
ease : Pyth on2 wasrel
eased inth e year2 0 0 0 wh ereasPyth on3 was
rel
eased inth e year2 0 0 8 .
6 . V ariabl
e L eakage : InPyth on, ifth e gl
obalvariabl
esare used inside afor- l
oop, th eir
val
uesdo ch ange. W h ereas, th e val
ue ofvariabl
esneverch angesinPyth on3 .
DEPA R T M EN T O F C SE, M B SC ET 3
PR O G R A M M IN G W IT H PY T H O N
1 0 . U sage InT oday’ sT imes: Since 2 0 2 0 , Pyth on2 h asbeenoutdated foruse wh ereas
Pyth on3 isstil
linuse by th e devel
opersand ismore popul
arth anPyth on2 .
1 1 . B ackward C ompatibil
ity : Itispossibl
e to portPyth on2 code to Pyth on3 butto do
th isal
otofeffortisrequired. O nth e oth erh and, Pyth on3 isnotbackwardscompatibl
e with
Pyth on2 .
1 2 . A ppl
ication: T h e util
isationofPyth on2 wasdone mostl
y to become aDevO ps
Engineer. N ow itisno l
ongerinuse after2 0 2 0 .
1 . 4 F EA T U R ES IN P Y T H O N
DEPA R T M EN T O F C SE, M B SC ET 4
PR O G R A M M IN G W IT H PY T H O N
Pyth onl
anguage and anybody canl
earnPyth onbasicsinafew h oursordays. Itisal
so adevel
oper-
friendl
ylanguage.
9. Pyth onisaPortabl
elanguage : Pyth onl
anguage isal
so aportabl
elanguage. F orexampl
e, if
we h ave Pyth oncode forW indowsand ifwe wantto runth iscode onoth erpl
atformssuch asL inux,
U nix, and M acth enwe do notneed to ch ange it, we canrunth iscode onany pl
atform.
DEPA R T M EN T O F C SE, M B SC ET 5
PR O G R A M M IN G W IT H PY T H O N
13. Dynamical
ly T yped L anguage : Pyth onisadynamical
ly- typed l
anguage. T h atmeansth e
type ( forexampl
e- int, doubl
e, l
ong, etc. ) foravariabl
e isdecided atruntime notinadvance because of
th isfeature we don’ tneed to specify th e type ofvariabl
e.
1 5 . Al
locatingM emory Dynamical
ly : InPyth on, th e variabl
e datatype doesnotneed to be
specified. T h e memory isautomatical
ly al
located to avariabl
e atruntime wh enitisgivenaval
ue.
Devel
opersdo notneed to write inty = 1 8 ifth e integerval
ue 1 5 issetto y. Y oumay justtype y= 1 8 .
1 . 5 B A SIC SY N T A X IN P Y T H O N
1 . 5 . 1 Identifiersinpyth on
IdentifiersinPyth onare used to identify variabl
es, objects, cl
asses, functions, and oth er
identifiers. T h ey are significantinwritingeffective code inth e Pyth onprogrammingl
anguage
asth ey make compl
exprogrammingtaskssimpl
er. A l
lidentifiersh ave aspecificsetofrul
es
th atneed to be fol
lowed wh il
e creatingidentifiers: th ey sh oul
d beginwith eith eranal
ph abet( a-
z ) oranunderscore ( _) , and afterth atcancontainany combinationofal
ph anumericch aracters
DEPA R T M EN T O F C SE, M B SC ET 6
PR O G R A M M IN G W IT H PY T H O N
( a- z , 0 - 9 ) . M oreover, identifiersare case- sensitive so it’ simportantto note th at'x'and 'X 'woul
d
be considered two differentidentifiers.
2. Inth isl
anguage, ifanidentifierstartswith asingl
eleadingunderscore th atcanindicate
th atth e particul
aridentifierisaprivate identifier.
3. Inth isl
anguage ifanidentifierstartswith two l
eadingunderscoresth atcanindicate a
strongl
y private identifier.
4. InPyth onprogrammingl
anguage Ifth e identifierendswith two trail
ingunderscores
th enth e identifiercanbe cal
led by al
anguage- defined specialname.
T abl
e 1 . 1 : P yth onK eywords
and as assert
break cl
ass continue
def del el
if
el
se except F al
se
final
ly for from
gl
obal if import
in is l
ambda
N one nonl
ocal not
DEPA R T M EN T O F C SE, M B SC ET 7
PR O G R A M M IN G W IT H PY T H O N
or pass raise
wh il
e with yiel
d
Pyth onprogrammingl
anguage doesnotprovide any bracesto indicate th e code bl
ocks
forfunctiondefinitionsorcl
assorfl
ow control
. T h e codesare denoted by l
ine identification.
T h e use ofindentationinPyth oniscrucial
. Itpl
aysanimportantrol
e inmakingPyth oncode
easierto read, fol
low, and use - wh il
e incorrectl
y formatted code canbe difficul
tto deciph erand
use. Indentationprovidesvisualstructure to yourcode and h asabigimpactonth e readabil
ity of
th e code. Indentational
so h el
pswith debugging, asmisal
igned statementscaneasil
y h el
pyou
identify th e errors. InPyth on, indentationisused to sh ow agroupofrel
ated statements, so
properuse ofindentationincreasesth e productivity ofdevel
operstoo. W ith outit, understanding
evensimpl
e programsinPyth onwoul
d be al
mostimpossibl
e.
Exampl
e C ode :
# T h isisacomment
# C ommentsstartwith a'# 'symboland are notexecuted
# Define avariabl
e
my_variabl
e= 4 2
# U se anifstatementwith indentation
ifmy_variabl
e> 5 0 :
print( " T h e variabl
e isgreaterth an5 0 " )
el
se: print( " T h e variabl
e isnotgreaterth an5 0 " )
# Define afunction
defgreet( name) :
print( " H el
lo, " + name + " ! " ) # C al
lth e functiongreet( " A l
ice" ) greet( " B ob" )
DEPA R T M EN T O F C SE, M B SC ET 8
PR O G R A M M IN G W IT H PY T H O N
1 . 5 . 3 P yth onM ul
ti- L ine Statem ents
Pyth onenabl
esmul
ti- l
ine statementsby al
lowingyouto continue astatementonto th e
fol
lowingl
ine by usingbacksl
ash es( \) . Th ish el
psmake code easierto compreh end and breaks
upl
ength y expressionsinto many l
inesforeasiercompreh ension. A sanal
ternative, youcan
create mul
ti- l
ine statementswith outth e usage ofbacksl
ash esby usingparenth esesorbrackets
fordatastructuresl
ike l
ists, dictionaries, ortupl
es.
Exampl
e C ode :
resul
t= 1 + \
2 + \
3 + \
4 + \
5
print( resul
t)
1 . 5 . 4 Q uotationsinP yth on
Pyth onquotesare agreatway to expressth ough tsand opinions, and Pyth onmakesit
easy to use th em incode. Doubl
e quotesinPyth onprovide two differenttypesofquoting: raw
stringsand regul
arstringl
iteral
s. R aw stringsare bestforspecifyingfixed patternswh ena
backsl
ash isused asanescape ch aracter, wh ereasregul
arstringl
iteral
smustbe encl
osed in
doubl
e quoteswh enth e backsl
ash needsto be used asanescape ch aracter. W h endeal
ingwith
Pyth onquotes, it'simportantto rememberto use th e same type ofquote wh enstartingand
endingyourstrings; oth erwise, syntaxerrorsmay occur. W ith th e righ tknow- h ow, pyth on
quotationscanh el
pmake yourcode more concise and readabl
e.
Exampl
e C ode :
# T h isisadoubl
e quotes
print( " H el
lo, W orl
d! " )
DEPA R T M EN T O F C SE, M B SC ET 9
PR O G R A M M IN G W IT H PY T H O N
1 . 5 . 5 M ul
tipl
e Statem entsonaSingl
e L ine
Semicol
ons( ; ) are used inPyth onto separate l
inescontainingseveralstatements.
Inorderto ensure readabil
ity, th isconcise syntaxsh oul
d onl y.
y be used sparingl
Exampl
e C ode :
a= 1 ; b= 2 ; c= a+ b
DEPA R T M EN T O F C SE, M B SC ET 1 0
PR O G R A M M IN G W IT H PY T H O N
C H A P T E R - 2
U SIN G V A R IA B L ES IN P Y T H O N
2 . 1 IN T R O DU C T IO N
Pyth onDatatypesare th e cl
assificationorcategoriz ationofdataitems. Itrepresentsth e kind ofval
ue
th attel
lswh atoperationscanbe performed onaparticul
ardata. Since everyth ingisanobjectinPyth on
programming, Pyth ondatatypesare cl
assesand variabl
esare instances( objects) ofth ese cl
asses. T h e
fol
lowingare th e standard orbuil
t- indatatypesinPyth on: N umeric, Sequence T ype, B ool
ean, Set,
Dictionary.
DEPA R T M EN T O F C SE, M B SC ET 1 1
PR O G R A M M IN G W IT H PY T H O N
Exampl
e C ode :
x= " H el
lo W orl
d"
x= 5 0
e" : 2 4 }
x= { " geeks" , " for" , " geeks" }
x= froz enset( { " geeks" , " for" , " geeks" })
x= T ruex= 6 0 . 5
x= 3 j
x= [" geeks" , " for" , " geeks" ]
x= ( " geeks" , " for" , " geeks" )
x= range( 1 0 )
x= { " name" : " Suraj" , " ag
x= bytearray( 4 )
x= memoryview( bytes( 6 ) )
x= N one
1. Integers– T h isval
ue isrepresented by intcl
ass. Itcontainspositive ornegative wh ol
e numbers
( with outfractionsordecimal
s) . InPyth on, th ere isno l
imitto h ow l
onganintegerval
ue canbe.
2. F l
oat– T h isval
ue isrepresented by th e fl
oatcl
ass. Itisarealnumberwith afl
oating- point
representation. Itisspecified by adecimalpoint. O ptional
ly, th e ch aractere orEfol
lowed by apositive
ornegative integermay be appended to specify scientificnotation.
3. C ompl
exN umbers– A compl
exnumberisrepresented by acompl
excl
ass. Itisspecified as( real
part) + ( imaginary part) j. F orexampl
e – 2 + 3 j.
DEPA R T M EN T O F C SE, M B SC ET 1 2
PR O G R A M M IN G W IT H PY T H O N
N ote – type( ) function isused to determine th e type ofPyth ondatatype.
Exampl
e: T h iscode demonstratesh ow to determine th e datatype ofvariabl
esinPyth onusingth e type( )
function. Itprintsth e datatypesofth ree variabl
es: a( integer) , b( fl
oat) , and c( compl
ex) . T h e output
sh owsth e respective datatype Pyth onforeach variabl
e.
O utput:
T ype ofa: < cl
ass'int'>
T ype ofb: < cl
ass'fl
oat'>
T ype ofc: < cl
ass'compl
ex'>
T abl
e 2 . 1 : N um ericDataT ype Exam pl
es
IN T LON G FLOAT C O M P L EX
1 0 5 1 9 2 4 3 6 1 L 0 .0 3 .1 4 j
1 0 0 - 0 x1 9 3 2 3 L 1 5 .2 0 4 5 .j
-7 8 6 0 1 2 2 L - 2 1 .9 9 . 3 2 2 e- 3 6 j
0 8 0 0 xDEF A B C EC B DA EC B F B A El 3 2 . 3 + e1 8 .8 7 6 j
-0 4 9 0 5 3 5 6 3 3 6 2 9 8 4 3 L -9 0 . - .6 5 4 5 + 0 J
- 0 x2 6 0 -0 5 2 3 1 8 1 7 2 7 3 5 L - 3 2 . 5 4 e1 0 0 3 e+ 2 6 J
0 x6 9 -4 7 2 1 8 8 5 2 9 8 5 2 9 L 7 0 . 2 - E1 2 4 . 5 3 e- 7 j
DEPA R T M EN T O F C SE, M B SC ET 1 3
PR O G R A M M IN G W IT H PY T H O N
T h e sequence DataT ype inPyth onisth e ordered col
lectionofsimil arordifferentPyth ondatatypes.
Sequencesal low storingofmul tiple val
uesinanorganiz ed and efficientfash ion. T h ere are several
sequence datatypesofPyth on: Pyth onString, Pyth onL ist, Pyth onT upl
e.
2 . 4 . 1 StringDataT ype
String1 = 'W el
come to th e G eeksW orl
d'
print( " Stringwith th e use ofSingl
e Q uotes: " )
print( String1 )
String1 = " I'm aG eek"
print( " \nStringwith th e use ofDoubl
e Q uotes: " )
print( String1 )
print( type( String1 ) )
String1 = '''I'm aG eek and Il
ive inaworl
d of" G eeks" '''
print( " \nStringwith th e use ofT ripl
e Q uotes: " )
print( String1 )
print( type( String1 ) )
String1 = '''G eeks F or L ife'''
print( " \nC reatingamul
til
ine String: " )
print( String1 )
O utput:
DEPA R T M EN T O F C SE, M B SC ET 1 4
PR O G R A M M IN G W IT H PY T H O N
Stringwith th e use ofSingl
e Q uotes:
W el
come to th e G eeksW orl
d
Stringwith th e use ofDoubl
e Q uotes:
I'm aG eek
< cl
ass'str'>
Stringwith th e use ofT ripl
e Q uotes:
I'm aG eek and Il
ive inaworl
d of" G eeks"
< cl
ass'str'>
C reatingamul
til
ine String:
G eeks
F or
L ife
2. A ccessingel
ementsofString: InPyth onprogramming , individualch aractersofa
O utput:
DEPA R T M EN T O F C SE, M B SC ET 1 5
PR O G R A M M IN G W IT H PY T H O N
InitialString:
G eeksF orG eeks
F irstch aracterofStringis:
G
L astch aracterofStringis:
s
2 . 4 . 2 L istDataT ype
Exampl
e: T h isPyth oncode demonstratesl
istcreationand manipul
ation. Itstartswith an
empty l
istand printsit. Itcreatesal
istcontainingasingl
e stringel
ementand printsit. Itcreates
al
istwith mul
tipl
e stringel
ementsand printssel
ected el
ementsfrom th e l
ist. Itcreatesamul
ti-
dimensionall
ist( al
istofl
ists) and printsit. T h e code sh owcasesvariouswaysto work with l
ists,
incl
udingsingl
e and mul
ti- dimensionall
ists.
DEPA R T M EN T O F C SE, M B SC ET 1 6
PR O G R A M M IN G W IT H PY T H O N
O utput:
Initialbl
ank L ist:
[]
L istwith th e use ofString:
['G eeksF orG eeks']
L istcontainingmul
tipl
e val
ues:
G eeks
G eeks
M ul
ti- DimensionalL ist:
[['G eeks', 'F or'], ['G eeks']]
O utput:
A ccessingel
ementfrom th e l
ist
G eeks
G eeks
A ccessingel
ementusingnegative indexing
G eeks
G eeks
DEPA R T M EN T O F C SE, M B SC ET 1 7
PR O G R A M M IN G W IT H PY T H O N
2 . 4 . 3 T upl
e DataT ype
Justl
ike al
ist, atupl
e isal
so anordered col
lectionofPyth onobjects. T h e onl
y
difference betweenatupl
e and al
ististh attupl
esare immutabl
e i. e. tupl
escannotbe modified
afteritiscreated. Itisrepresented by atupl
e cl
ass.
1. C reatingaT upl
e inPyth on: InPyth onDataT ypes, tupl
es are created by pl
acinga
sequence ofval
uesseparated by a‘comma’ with orwith outth e use ofparenth esesforgrouping
th e datasequence. T upl
escancontainany numberofel
ementsand ofany datatype ( l
ike strings,
integers, l
ists, etc. ) . N ote: T upl
escanal
so be created with asingl
e el
ement, butitisabittricky.
H avingone el
ementinth e parenth esesisnotsufficient, th ere mustbe atrail
ing‘comma’ to
make itatupl
e.
Exampl
e: T h isPyth oncode demonstratesdifferentmeth odsofcreatingand working
with tupl
es. Itstartswith anempty tupl
e and printsit. Itcreatesatupl
e containingstring
el
ementsand printsit. Itconvertsal
istinto atupl
e and printsth e resul
t. Itcreatesatupl
e from a
stringusingth e tupl
e( ) function. Itformsatupl
e with nested tupl
esand displ
aysth e resul
t.
T upl
e1 = ( )
print( " Initialempty T upl
e: " )
print( T upl
e1 )
T upl
e1 = ( 'G eeks', 'F or')
print( " \nT upl
e with th e use ofString: " )
print( T upl
e1 )
l
ist1 = [1 , 2 , 4 , 5 , 6 ]
print( " \nT upl
e usingL ist: " )
print( tupl
e( l
ist1 ) )
T upl
e1 = tupl
e( 'G eeks')
print( " \nT upl
e with th e use offunction: " )
print( T upl
e1 )
T upl
e1 = ( 0 , 1 , 2 , 3 )
T upl
e2 = ( 'pyth on', 'geek')
DEPA R T M EN T O F C SE, M B SC ET 1 8
PR O G R A M M IN G W IT H PY T H O N
T upl
e3 = ( T upl
e1 , T upl
e2 )
print( " \nT upl
e with nested tupl
es: " )
print( T upl
e3 )
O utput:
Initialempty T upl
e:
()
T upl
e with th e use ofString:
( 'G eeks', 'F or')
T upl
e usingL ist:
(1 , 2 , 4 , 5 , 6 )
T upl
e with th e use offunction:
( 'G ', 'e', 'e', 'k', 's')
T upl
e with nested tupl
es:
( ( 0 , 1 , 2 , 3 ) , ( 'pyth on', 'geek') )
2. A ccessT upl
e Items: Inorderto accessth e tupl
e itemsreferto th e indexnumber. U se
th e indexoperator[]to accessanitem inatupl
e. T h e indexmustbe aninteger. N ested tupl
es
are accessed usingnested indexing.
Exampl
e : T h e code createsatupl e1 ′ with five el
e named ‘tupl ements: 1 , 2 , 3 , 4 , and 5 .
T h enitprintsth e first, l
ast, and th ird l
astel
ementsofth e tupl
e usingindexing.
tupl
e1 = tupl
e( [1 , 2 , 3 , 4 , 5 ])
print( " F irstel
ementoftupl
e" )
print( tupl
e1 [0 ])
print( " \nL astel
ementoftupl
e" )
print( tupl
e1 [- 1 ])
print( " \nT h ird l
astel
ementoftupl
e" )
print( tupl
e1 [- 3 ])
O utput:
F irstel
ementoftupl
e
DEPA R T M EN T O F C SE, M B SC ET 1 9
PR O G R A M M IN G W IT H PY T H O N
1
L astel
ementoftupl
e
5
T h ird l
astel
ementoftupl
e
3
2 . 4 . 4 B ool
eanDataT ype
Exampl
e: T h e firsttwo l
ineswil
lprintth e type ofth e bool
eanval
uesT rue and F al
se,
wh ich is< cl
ass‘bool
’ > . T h e th ird l
ine wil
lcause anerror, because true isnotaval
id keyword in
Pyth on. Pyth oniscase- sensitive, wh ich meansitdistinguish esbetweenuppercase and l
owercase
l
etters. Y ouneed to capital
iz e th e firstl
etteroftrue to make itabool
eanval
ue.
O utput:
< cl
ass'bool
'>
< cl
ass'bool
'>
T raceback ( mostrecentcal
llast) :
F il
e " / h ome/ 7 e8 8 6 2 7 6 3 fb6 6 1 5 3 d7 0 8 2 4 0 9 9 d4 f5 fb7 . py" , l
ine 8 , in
print( type( true) )
N ameError: name 'true'isnotdefined
DEPA R T M EN T O F C SE, M B SC ET 2 0
PR O G R A M M IN G W IT H PY T H O N
2 . 4 . 5 SetDataT ype
Exampl
e: T h e code isanexampl
e ofh ow to create setsusingdifferenttypesofval
ues,
such asstrings, l
ists, and mixed val
ues
set1 = set( )
print( " Initialbl
ank Set: " )
print( set1 )
set1 = set( " G eeksF orG eeks" )
print( " \nSetwith th e use ofString: " )
print( set1 )
set1 = set( [" G eeks" , " F or" , " G eeks" ])
print( " \nSetwith th e use ofL ist: " )
print( set1 )
set1 = set( [1 , 2 , 'G eeks', 4 , 'F or', 6 , 'G eeks'])
print( " \nSetwith th e use ofM ixed V al
ues" ) print( set1 )
O utput:
Initialbl
ank Set:
set( )
Setwith th e use ofString:
{ 'F ', 'o', 'G ', 's', 'r', 'k', 'e'}
Setwith th e use ofL ist:
{ 'G eeks', 'F or'}
DEPA R T M EN T O F C SE, M B SC ET 2 1
PR O G R A M M IN G W IT H PY T H O N
Setwith th e use ofM ixed V al
ues
{ 1 , 2 , 4 , 6 , 'G eeks', 'F or'}
Exampl
e: T h isPyth oncode createsasetnamed set1 with th e
val
ues“ G eeks”, “ F or”and “ G eeks”. T h e code th enprintsth e initialset, th e el
ementsofth e set
inal
oop, and ch ecksifth e val
ue “ G eeks”isinth e setusingth e ‘in’ operator
O utput:
Initialset:
{ 'G eeks', 'F or'}
El
ementsofset:
G eeksF or
T rue
DEPA R T M EN T O F C SE, M B SC ET 2 2
PR O G R A M M IN G W IT H PY T H O N
1. C reate aDictionary inPyth on: InPyth on, aDictionary canbe created by pl
acinga
sequence ofel
ementswith incurl
y { } braces, separated by ‘comma’ . V al
uesinadictionary can
be ofany datatype and canbe dupl
icated, wh ereaskeyscan’ tbe repeated and mustbe
immutabl
e. T h e dictionary canal
so be created by th e buil
t- infunctiondict( ) . A nempty
dictionary canbe created by justpl
acingitincurl
y braces{ }. N ote – Dictionary keysare case
sensitive, th e same name butdifferentcasesofK ey wil
lbe treated distinctl
y.
Exampl
e: T h iscode createsand printsavariety ofdictionaries. T h e firstdictionary is
empty. T h e second dictionary h asintegerkeysand stringval
ues. T h e th ird dictionary h asmixed
keys, with one stringkey and one integerkey. T h e fourth dictionary iscreated using
th e dict( ) function, and th e fifth dictionary iscreated usingth e [( key, val
ue) ]syntax.
Dict= { }
print( " Empty Dictionary: " )
print( Dict)
Dict= { 1 : 'G eeks', 2 : 'F or', 3 : 'G eeks'}
print( " \nDictionary with th e use ofIntegerK eys: " )
print( Dict)
Dict= { 'N ame': 'G eeks', 1 : [1 , 2 , 3 , 4 ]}
print( " \nDictionary with th e use ofM ixed K eys: " )
print( Dict)
Dict= dict( { 1 : 'G eeks', 2 : 'F or', 3 : 'G eeks'})
print( " \nDictionary with th e use ofdict( ) : " )
print( Dict)
Dict= dict( [( 1 , 'G eeks') , ( 2 , 'F or') ])
print( " \nDictionary with each item asapair: " )
print( Dict)
O utput:
Empty Dictionary:
{}
Dictionary with th e use ofIntegerK eys:
{ 1 : 'G eeks', 2 : 'F or', 3 : 'G eeks'}
DEPA R T M EN T O F C SE, M B SC ET 2 3
PR O G R A M M IN G W IT H PY T H O N
Dictionary with th e use ofM ixed K eys:
{ 1 : [1 , 2 , 3 , 4 ], 'N ame': 'G eeks'}
Dictionary with th e use ofdict( ) :
{ 1 : 'G eeks', 2 : 'F or', 3 : 'G eeks'}
Dictionary with each item asapair:
{ 1 : 'G eeks', 2 : 'F or'}
Exampl
e: T h e code inPyth onisused to accessel
ementsinadictionary. H ere’ swh atit
does, Itcreatesadictionary Dictwith keysand val
uesas{ 1 : ‘G eeks’ , ‘name’ : ‘F or’ , 3 :
‘G eeks’ } . Itprintsth e val
ue ofth e el
ementwith th e key ‘name’ , wh ich is‘F or’ . Itprintsth e
val
ue ofth e el
ementwith th e key 3 , wh ich is‘G eeks’ .
O utput:
A ccessingael
ementusingkey:
F or
A ccessingael
ementusingget:
G eeks
DEPA R T M EN T O F C SE, M B SC ET 2 4
PR O G R A M M IN G W IT H PY T H O N
C H A P T E R - 3
B A SIC P R O G R A M M IN G IN P Y T H O N
3 . 1 IN T R O DU C T IO N
C onditional
sal
low usto make decisionsinourcode. B y usingstatementsl
ike if, el
if, and el
se, we can
execute differentbl
ocksofcode based onspecificconditions. T h isenabl
esourprogramsto respond
dynamical
ly to varyinginputsand situations. L oopsare powerfulconstructsth atenabl
e usto repeata
bl
ock ofcode mul
tipl
e times. W e wil
ldel
ve into two primary typesofl
oopsinPyth on: forl
oopsand
wh il
eloops. T h ese tool
sare inval
uabl
e fortasksth atrequire iteration, such asprocessingitemsinal
ist
orexecutingabl
ock ofcode untilacertainconditionismet. F unctionsare reusabl
e piecesofcode th at
perform aspecifictask. B y definingfunctions, we canorganiz e ourcode into manageabl
e sections,
makingiteasierto read, maintain, and debug. W e wil
llearnh ow to create functions, passarguments,
and returnval
ues, wh ich wil
lenh ance ourprogrammingefficiency. F inal
ly, we wil
lexpl
ore modul
es,
wh ich are fil
escontainingPyth oncode th atcanbe imported and used inoth erprograms. M odul
esal
low
usto organiz e ourcode into separate fil
es, promotingreusabil
ity and modul
arity. W e wil
ldiscussh ow
to create ourownmodul
esand h ow to l
everage existingonesfrom th e Pyth onStandard L ibrary.
3 . 2 C O N DIT IO N A L ST A T EM EN T S
SyntaxofIfStatement:
ifcondition:
# Statementsto execute if
# conditionistrue
DEPA R T M EN T O F C SE, M B SC ET 2 5
PR O G R A M M IN G W IT H PY T H O N
C ode:
if1 0 > 5 :
print( " 1 0 greaterth an5 " )
print( " Program ended" )
O utput:
1 0 greaterth an5
Program ended
3 . 2 . 2 Ifel
se C onditionalStatem entinP yth on
InaconditionalifStatementth e additionalbl
ock ofcode ismerged asanel
se statement
wh ich isperformed wh enifconditionisfal
se.
SyntaxofPyth onIf- El
se:
if( condition) :
# Executesth isbl
ock if
# conditionistrue
el
se:
# Executesth isbl
ock if
# conditionisfal
se
C ode:
x= 3
ifx= = 4 :
print( " Y es" )
el
se:
print( " N o" )
O utput:
N o
DEPA R T M EN T O F C SE, M B SC ET 2 6
PR O G R A M M IN G W IT H PY T H O N
3 . 2 . 3 N ested if. . el
se C onditionalStatem entinP yth on
N ested if. . el
se meansanif- el
se statementinside anoth erifstatement. O rinsimpl
e words
first, th ere isanouterifstatement, and inside itanoth erif– el
se statementispresentand such
type ofstatementisknownasnested ifstatement. W e canuse one iforel
se ifstatementinside
anoth eriforel
se ifstatements.
C ode:
l
etter= " A "
ifl
etter= = " B " :
print( " l
etterisB " )
el
se:
ifl
etter= = " C " :
print( " l
etterisC " )
el
se:
ifl
etter= = " A " :
print( " l
etterisA " )
el
se:
print( " l
etterisn'tA , B and C " )
O utput:
l
etterisA
3 . 2 . 4 If- el
if- el
se C onditionalStatem entsinP yth on
T h e ifstatementsare executed from th e topdown. A ssoonasone ofth e conditions
control
lingth e ifistrue, th e statementassociated with th atifisexecuted, and th e restofth e
l
adderisbypassed. Ifnone ofth e conditionsistrue, th enth e final“ el
se”statementwil
lbe
executed.
C ode:
l
etter= " A "
ifl
etter= = " B " :
print( " l
etterisB " )
el
ifl
etter= = " C " :
DEPA R T M EN T O F C SE, M B SC ET 2 7
PR O G R A M M IN G W IT H PY T H O N
print( " l
etterisC " )
el
ifl
etter= = " A " :
print( " l
etterisA " )
el
se:
print( " l
etterisn'tA , B orC " )
O utput:
l
etterisA
Syntax: [on_true]if[expression]el
se [on_fal
se]
expression: conditional
_expression| l
ambda_expr
C ode:
a= 2 , b= 1 0
print( " B oth aand bare equal
" ifa= = bel
se " aisgreaterth anb"
ifa> bel
se " bisgreaterth ana" )
O utput:
bisgreaterth ana
3 . 3 L O O P IN G ST A T EM EN T S
DEPA R T M EN T O F C SE, M B SC ET 2 8
PR O G R A M M IN G W IT H PY T H O N
Pyth onprogrammingl
anguage providestwo typesofPyth onl
oopsh eckingtime : F orl
oopand W h il
e
l
oopto h andl
eloopingrequirements.
3 . 3 . 1 W h il
e L oopinP yth on
InPyth on, awh il
eloopisused to execute abl
ock ofstatementsrepeatedl
y untilagiven
conditionissatisfied. W h enth e conditionbecomesfal
se, th e l
ine immediatel
y afterth e l
oopin
th e program isexecuted.
Pyth onW h il
e L oopSyntax:
wh il
e expression:
statement( s)
Al
lth e statementsindented by th e same numberofch aracterspacesafteraprogramming
constructare considered to be partofasingl
e bl
ock ofcode. Pyth onusesindentationasits
meth od ofgroupingstatements.
Exampl
e: T h e givenPyth oncode usesa‘wh il
e'l
oopto print“ H el
lo G eek”th ree times
by incrementingavariabl
e cal
led ‘count'from 1 to 3 .
count= 0
wh il
e ( count< 3 ) :
count= count+ 1
print( " H el
lo G eek" )
O utput:
H el
lo G eek
H el
lo G eek
H el
lo G eek
3 . 3 . 2 F or L oopinP yth on
DEPA R T M EN T O F C SE, M B SC ET 2 9
PR O G R A M M IN G W IT H PY T H O N
F orl
oopsare used forsequentialtraversal
. F orexampl
e: traversing
al
ist orstringorarray etc. InPyth on, th ere is“ forin”l
oopwh ich issimil
arto foreach l
oopin
oth erl
anguages. Itcanbe used to iterate overarange and iterators.
F orL oopSyntax:
foriterator_varinsequence:
statements( s)
Exampl
e:
T h e code usesaPyth onforl
oopth atiteratesoverth e val
uesfrom 0 to 3 ( notincl
uding
4 ) , asspecified by th e range( 0 , n) construct. Itwil
lprintth e val
uesof‘i'ineach iterationofth e
l
oop.
n= 4
fori inrange( 0 , n) :
print( i)
O utput:
0
1
2
3
F unctionisabl
ock ofstatementsth atreturnth e specifictask. T h e ideaisto putsome commonl
y
orrepeatedl
y done taskstogeth erand make afunctionso th atinstead ofwritingth e same code again
and againfordifferentinputs, we cando th e functioncal
lsto reuse code contained initoverand over
again.
DEPA R T M EN T O F C SE, M B SC ET 3 0
PR O G R A M M IN G W IT H PY T H O N
Exampl
e:
deffun( ) :
print( " W el
come to G F G " )
3 . 4 . 2 C al
lingaF unctioninP yth on
DEPA R T M EN T O F C SE, M B SC ET 3 1
PR O G R A M M IN G W IT H PY T H O N
A ftercreatingafunctioninPyth onwe cancal
litby usingth e name ofth e functions
fol
lowed by parenth esiscontainingparametersofth atparticul
arfunction.
Exampl
e:
num1 , num2 = 5 , 1 5
ans= add( num1 , num2 )
print( f" T h e additionof{ num1 } and { num2 } resul
ts{ ans}. " )
DEPA R T M EN T O F C SE, M B SC ET 3 2
PR O G R A M M IN G W IT H PY T H O N
C H A P T E R - 4
O B JEC T O R IEN T ED P R O G R A M M IN G IN P Y T H O N
4 . 1 IN T R O DU C T IO N
O O P C oncepts:
Cl
assinPyth on
O bjectsinPyth on
Pol
ymorph ism inPyth on
Encapsul
ationinPyth on
DataA bstractioninPyth on
4 . 2 P yth onC l
ass
A cl
assisacol
lectionofobjects. A cl
asscontainsth e bl
ueprintsorth e prototype from wh ich th e objects
are beingcreated. Itisal
ogicalentity th atcontainssome attributesand meth ods.
DEPA R T M EN T O F C SE, M B SC ET 3 3
PR O G R A M M IN G W IT H PY T H O N
1. C l
assesare created by keyword cl
ass.
2. A ttributesare th e variabl
esth atbel
ongto acl
ass.
3. A ttributesare al
wayspubl
icand canbe accessed usingth e dot( . ) operator.
Eg. : M ycl
ass. M yattribute
Cl
assDefinitionSyntax:
cl
assC l assN ame:
# Statement- 1
.
.
.
# Statement- N
Exampl
e:
cl
assDog:
pass
A nobjectconsistsof:
DEPA R T M EN T O F C SE, M B SC ET 3 4
PR O G R A M M IN G W IT H PY T H O N
B eh avior: Itisrepresented by th e meth odsofanobject. Ital
so refl
ectsth e response ofanobjectto oth er
objects.
C reatinganO bject:
T h iswil
lcreate anobjectnamed objofth e cl
assDogdefined above.
obj= Dog( )
4 . 4 T h e P yth onsel
f
Cl
assmeth odsmusth ave anextrafirstparameterinth e meth od definition. W e do notgive aval
ue for
th isparameterwh enwe cal
lth e meth od, Pyth onprovidesit. Ifwe h ave ameth od th attakesno
arguments, th enwe stil
lh ave to h ave one argument. T h isissimil
arto th ispointerinC + + and th is
reference inJava.
W h enwe cal
lameth od ofth isobjectasmyobject. meth od( arg1 , arg2 ) , th isisautomatical
ly converted
by Pyth oninto M yC l
ass. meth od( myobject, arg1 , arg2 ) – th isisal
lth e specialsel
fisabout.
T h e __init__meth od issimil
arto constructorsinC + + and Java. Itisrunassoonasanobjectofacl
ass
isinstantiated. T h e meth od isusefulto do any initial
iz ationyouwantto do with yourobject. N ow l
etus
define acl
assand create some objectsusingth e sel
fand __init__meth od.
C reatingacl
assand objectwith cl
assand instance attributes
DEPA R T M EN T O F C SE, M B SC ET 3 5
PR O G R A M M IN G W IT H PY T H O N
cl
assDog:
# cl
assattribute
# Instance attribute
def__init__( sel
f, name) :
sel
f. name = name
# Drivercode
# O bjectinstantiation
# A ccessingcl
assattributes
# A ccessinginstance attributes
O utput
R odgerisamammal
T ommy isal
so amammal
Itrepresentsreal
- worl
d rel
ationsh ipswel
l.
Itprovidesth e reusabil
ity ofacode. W e don’ th ave to write th e same code againand again. A l
so, it
al
lowsusto add more featuresto acl
asswith outmodifyingit.
T ypesofInh eritance
Singl
e Inh eritance: Singl
e- l
evelinh eritance enabl
esaderived cl
assto inh eritch aracteristicsfrom a
singl
e- parentcl
ass.
M ul
til
evelInh eritance: M ul
ti- l
evelinh eritance enabl
esaderived cl
assto inh eritpropertiesfrom an
immediate parentcl
asswh ich inturninh eritspropertiesfrom h isparentcl
ass.
M ul
tipl
e Inh eritance: M ul
tipl
e- l
evelinh eritance enabl
esone derived cl
assto inh eritpropertiesfrom
more th anone base cl
ass.
4 . 7 P yth onP ol
ym orph ism
DEPA R T M EN T O F C SE, M B SC ET 3 7
PR O G R A M M IN G W IT H PY T H O N
Exampl e : T h iscode demonstratesth e conceptofPyth onoopsinh eritance and meth od overridingin
Pyth oncl asses. Itsh owsh ow subcl assescanoverride meth odsdefined inth eirparentcl
assto provide
specificbeh aviorwh il e stil
linh eritingoth ermeth odsfrom th e parentcl
ass.
cl
assB ird:
defintro( sel
f) :
deffl
igh t( sel
f) :
cl
asssparrow( B ird) :
deffl
igh t( sel
f) :
cl
assostrich ( B ird) :
deffl
igh t( sel
f) :
obj_bird = B ird( )
obj_spr= sparrow( )
obj_ost= ostrich ( )
obj_bird. intro( )
obj_bird. fl
igh t( )
DEPA R T M EN T O F C SE, M B SC ET 3 8
PR O G R A M M IN G W IT H PY T H O N
obj_spr. intro( ) obj_spr. fl
igh t( )
O utput
M ostofth e birdscanfl
y butsome cannot.
Sparrowscanfl
y.
O strich escannotfl
y.
4 . 8 P yth onEncapsul
ation
F ig4 . 1 : Encapsul
ation
DEPA R T M EN T O F C SE, M B SC ET 3 9
PR O G R A M M IN G W IT H PY T H O N
C H A P T E R - 5
C O N N EC T IN G T O SQ L IT E DA T A B A SE IN P Y T H O N
5 . 1 IN T R O DU C T IO N
pysql
ite isanexternall
ibrary inPyth onth atprovidesSQ L ite database access. Itwasth e original
interface to th e SQ L ite rel
ationaldatabase managementsystem before itbecame integrated into
Pyth on’ sstandard l
ibrary assql
ite3 . Since Pyth on2 . 5 and above, sql
ite3 isincl
uded inPyth on’ s
standard l
ibrary, wh ich essential
ly providesth e same functional
itiesaspysql
ite. Ifyouare usingPyth on
2 . 5 orl
ater, itisrecommended to use sql
ite3 instead. H ere’ sabasicexampl
e ofusingsql
ite3 :
SQ L ite isaC - l
anguage l
ibrary th atimpl
ementsasmal
l, fast, sel
f- contained, h igh - rel
iabil
ity, ful
l-
featured, SQ L database engine.
Itisembedded into th e end program. SQ L ite readsand writesdirectl
y to ordinary disk fil
es. A compl
ete
SQ L database with mul
tipl
e tabl
es, indices, triggers, and views, iscontained inasingl
e disk fil
e.
DEPA R T M EN T O F C SE, M B SC ET 4 0
PR O G R A M M IN G W IT H PY T H O N
Itisused predominantl
y forappl
icationsth atneed al
igh tweigh tdatabase with outth e need fora
network- accessibl
e database managementsyste
5 . 2 C O N N EC T IN G T O DA T A B A SE
sql
iteC onnection= sql
ite3 . connect( 'sql
. db')
T o execute some queriesafterth e connectionisbeingmade. F orth at, acursorh asto be created using
th e cursor( ) meth od onth e connectioninstance, wh ich wil
lexecute ourSQ L queries.
cursor= sql
iteC onnection. cursor( )
print( 'DB Init')
T h e bel
ow exampl
e wil
lconnectto anSQ L ite database and wil
lrunasimpl
e query sel
ect
sql
ite_version( ) ; to find th e versionofth e SQ L ite we are using.
Exampl
e:
DEPA R T M EN T O F C SE, M B SC ET 4 1
PR O G R A M M IN G W IT H PY T H O N
im portsql
ite3
try:
# Cl ose th e cursor
cursor. cl
ose( )
# H andl e errors
exceptsql ite3 . Erroraserror:
print( 'Erroroccurred - ', error)
ifsqliteC onnection:
sql iteC onnection. close( )
print( 'SQ L ite C onnectioncl
osed')
F ig5 . 1 : SQ L IT E C O N N EC T IO N IN P Y T H O N
5 . 3 SQ L IT E DA T A B A SE
1. SQ L ite isal
igh tweigh t, serverl
ess, sel
f- contained, and h igh l
y rel
iabl
e SQ L database engine. Itis
widel
y used due to itssimpl
icity, ease ofsetupand z ero- configurationnature.
4. O ne ofth e mainbenefitsofusingSQ L ite isth atitisvery easy to getstarted with . T o create anew
database inSQ L ite, yousimpl
y need to create anew fil
e onyourfil
esystem and connectto itusingth e
SQ L ite3 A PI.
5 . 3 . 1 A DV A N T A G ES O F SQ L IT E
1. Ease ofuse: SQ L ite isvery easy to getstarted with , asitrequiresno setuporconfiguration. Y oucan
simpl
y incl
ude th e l
ibrary inyourprojectand startusingit.
2. Embeddabil
ity: SQ L ite isdesigned to be embedded into oth erappl
ications. Itisasel
f- contained,
serverl
essdatabase engine, wh ich meansyoucanincl
ude itinyourappl
icationwith outth e need fora
separate database server.
DEPA R T M EN T O F C SE, M B SC ET 4 3
PR O G R A M M IN G W IT H PY T H O N
4. Serverl
ess: A smentioned earl
ier, SQ L ite isaserverl
essdatabase engine, wh ich meansth ere isno
need to setupand maintainaseparate database serverprocess. T h ismakesiteasy to depl
oy and
manage, asth ere are no additionaldependenciesto worry about.
5. C ross- pl
atform: SQ L ite isavail
abl
e onmany pl
atforms, incl
udingL inux, macO S, and W indows,
makingitagood ch oice forcross- pl
atform devel
opment.
6. Standal
one: SQ L ite storesal
lofth e datainasingl
e fil
e onth e fil
esystem, wh ich makesiteasy to
copy orbackupth e database.
7. H igh rel
iabil
ity: SQ L ite h asbeenwidel
y tested and used inproductionsystemsformany years, and
h asareputationforbeingarel
iabl
e and robustdatabase engine.
5 . 3 . 2 SQ L IT E C O M M A N DS
InSQ L ite, DDL ( DataDefinitionL anguage) isused to create and modify database objectssuch as
tabl
es, indices, and views. Some exampl
esofDDL statementsinSQ L ite are:
C R EA T ET A B L E: createsanew tabl
e inth e database.
A L T ER T A B L E: modifiesanexistingtabl
e inth e database.
DR O P T A B L E: del
etesatabl
e from th e database.
DR O P IN DEX : del
etesanindexfrom atabl
e.
DM L ( DataM odificationL anguage) isused to modify th e datastored inth e database. Some exampl
es
DEL ET EF R O M : del
etesone ormore rowsfrom atabl
e
JO IN : retrievesdatafrom mul
tipl
e tabl
esbased onacommonfiel
d.
G R O U P B Y : groupsth e resul
tsofaquery by one ormore fiel
ds.
H A V IN G : fil
tersth e resul
tsofaquery based onacondition
C H A P T ER – 9
DEPA R T M EN T O F C SE, M B SC ET 4 5
PR O G R A M M IN G W IT H PY T H O N
A S S IG N M EN T
DEPA R T M EN T O F C SE, M B SC ET 4 6
PR O G R A M M IN G W IT H PY T H O N
DEPA R T M EN T O F C SE, M B SC ET 4 7
PR O G R A M M IN G W IT H PY T H O N
SO L U T IO N
DEPA R T M EN T O F C SE, M B SC ET 4 8
PR O G R A M M IN G W IT H PY T H O N
DEPA R T M EN T O F C SE, M B SC ET 4 9
PR O G R A M M IN G W IT H PY T H O N
DEPA R T M EN T O F C SE, M B SC ET 5 0
PR O G R A M M IN G W IT H PY T H O N
SO L U T IO N
# score_cal
cul
ator. py
defbatscore( x) :
runs= x['runs']
returnscore
defbowl
score( x) :
wkts= x['wkts']
fiel
ds= x['fiel
d']
economy_rate< 3 . 5 el
se 0 ) + ( 1 0 ifeconomy_rate< 2 el
se 0 )
returnscore
DEPA R T M EN T O F C SE, M B SC ET 5 1
PR O G R A M M IN G W IT H PY T H O N
# main. py
importscore_cal
cul
ator# Importingscore_cal
cul
atormodul
e
# G ivingInputsasdictionary
p2 = { 'name': 'duPl
essis', 'rol
e': 'bat', 'runs': 1 2 0 , '4 ': 1 1 , '6 ': 2 , 'bal
ls': 1 1 2 , 'fiel
d': 0 }
p5 = { 'name': 'K ul
deepY adav', 'rol
e': 'bowl
', 'wkts': 3 , 'overs': 1 0 , 'runs': 3 4 , 'fiel
d': 0 }
pl
ayers= [p1 , p2 , p3 , p4 , p5 ] # M akingal
istofdictionariesso th atwe caniterate th rough each dictionary
scores= { }
fori inpl
ayers:
ifi['rol
e']= = 'bat':
score = score_cal
cul
ator. batscore( i)
scores[i['name']]= score
el
se:
score = score_cal
cul
ator. bowl
score( i)
scores[i['name']]= score
DEPA R T M EN T O F C SE, M B SC ET 5 2
PR O G R A M M IN G W IT H PY T H O N
print( " 'name': { }, 'bowl
score': { }" . format( i['name'], score) )
print( " T h e maximum scoreris{ } with score { }" . format( max_scorer, max( scores. val
ues( ) ) ) )
DEPA R T M EN T O F C SE, M B SC ET 5 3
PR O G R A M M IN G W IT H PY T H O N
DEPA R T M EN T O F C SE, M B SC ET 5 4
PR O G R A M M IN G W IT H PY T H O N
SO L U T IO N
# main. py
cl
assbook:
def__init__( sel
f, a= 'C onceptofph ysics', b= 'R . K B ansal
', c= 'S> L A rorah ', d= 5 0 0 , q= 6 0 0 ) :
sel
f. titl
e= a
sel
f. auth or= b
sel
f. publ
ish er= c
sel
f. price= d
sel
f. quan= q
royal
= 0
defget_titl
e( sel
f) :
returnsel
f. _titl
e
defset_titl
e( sel
f, a) :
sel
f. titl
e= a
return
returnsel
f. auth or
sel
f. auth or= b
return
defget_publ
ish er( sel
f) :
returnsel
f. publ
ish er( )
defset_publ
ish er( sel
f, c) :
DEPA R T M EN T O F C SE, M B SC ET 5 5
PR O G R A M M IN G W IT H PY T H O N
sel
f. publ
ish er= c
return
defget_price( sel
f) :
returnsel
f. price
defset_price( sel
f, d) :
sel
f. price= d
return
defget_quan( sel
f) :
returnsel
f. quan
defset_quan( sel
f, e) :
sel
f. quan= e
return
defroyal
ty( sel
f) :
ifsel
f. quan< = 5 0 0 :
royal
= . 1 * sel
f. price* sel
f. quan
el
ifsel
f. quan> 5 0 0 and sel
f. quan< = 1 5 0 0 :
royal
= . 1 2 5 * sel
f. price* ( sel
f. quan- 5 0 0 ) + . 1 * sel
f. price* 5 0 0
el
ifsel
f. quan> 1 5 0 0 :
royal
= . 1 * sel
f. price* 5 0 0 + . 1 2 5 * sel
f. price* 1 0 0 0 + . 1 5 * sel
f. price* ( sel
f. quan- 1 5 0 0 )
returnroyal
cl
assebook( book) :
def__init( sel
f, aa= 'PDF ') :
sel
f. _fromat= aa
DEPA R T M EN T O F C SE, M B SC ET 5 6
PR O G R A M M IN G W IT H PY T H O N
defget_format( sel
f) :
returnsel
f. format
defset_format( sel
f, b) :
sel
f. format= b
return
defroyal
ty( sel
f) :
ifsel
f. quan< = 5 0 0 :
royal
= . 1 * sel
f. price* sel
f. quan
el
ifsel
f. quan> 5 0 0 and sel
f. quan< = 1 5 0 0 :
royal
= . 1 2 5 * sel
f. price* ( sel
f. quan- 5 0 0 ) + . 1 * sel
f. price* 5 0 0
el
ifsel
f. quan> 1 0 0 0 :
royal
= . 1 * sel
f. price* 5 0 0 + . 1 2 5 * sel
f. price* 1 0 0 0 + . 1 5 * sel
f. price* ( sel
f. quan- 1 5 0 0 )
royal
= royal
- ( . 1 2 * royal
)
returnroyal
f= int( input( " Enter1 fornormalbook and enter2 fore book " ) )
x= book( )
x. set_titl
e( a)
x. set_auth or( b)
x. set_publ
ish er( c)
x. set_price( d)
DEPA R T M EN T O F C SE, M B SC ET 5 7
PR O G R A M M IN G W IT H PY T H O N
x. set_quan( e)
y= ebook( )
iff= = 1 :
z = x. royal
ty( )
iff= = 2 :
z = y. royal
ty( )
y. set_format( g)
R oyal
ty is{ } \n" . format( y. titl
e, y. publ
ish er, y. auth or, y. price, y. quan, y. format, z ) )
DEPA R T M EN T O F C SE, M B SC ET 5 8
PR O G R A M M IN G W IT H PY T H O N
B IB L IO G R A P H Y
F orsuccessful
ly compl
etingmy projectreport, Ih ave takenreferencesfrom th e fol
lowing
DEPA R T M EN T O F C SE, M B SC ET 5 9