0% found this document useful (0 votes)
20 views71 pages

Project Report Aryan Batra 19 Sep

Project Report Aryan Batra 19 Sep

Uploaded by

ashishmattoo985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views71 pages

Project Report Aryan Batra 19 Sep

Project Report Aryan Batra 19 Sep

Uploaded by

ashishmattoo985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

M O O C R EP O R T

ON
P R O G R A M M IN G W IT H P Y T H O N

Submitted inth e partialful


fil
lmentofrequirementforth e award ofdegree

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

P rof. K iranpalK our

DepartmentofC omputerScience Engineering


M ah antB ach ittarSingh C ol
lege ofEngineeringand T ech nol
ogy, Jammu
2 0 2 4 -2 0 2 5
I

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.

Date : A ryanB atra


R ol
lN o : 1 3 / 2 3

C ertified th atth e above statementmade by th e studentiscorrectto th e bestofmy


knowl edge and bel ief.

M s. K iranpalK our

C ourse C oordinator, C SEDeptt


II

A C K N O W L EDG EM EN T

It is my fortune th at I h ad got opportunity to carry my M O O C course


“ PR O G R A M M IN G W IT H PY T H O N ” under th e supervision of Prof. K iranpal
K ourinth e departmentof C omputerScience Engineering, M ah antB ach ittarSingh
C ol
lege of Engineering and T ech nol
ogy ( M B SC ET ) , Jeevan N agar, Jammu
affil
iated to U niversity ofJammu. I woul
dlike to th anks from th e deepestofmy
h eartforguidingand sh aringth eirval
uabl
e knowl
edge with me.

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

Programming with Pyth on begins by famil


iariz ing onesel
fwith th e process ofinstal
ling Pyth on

and navigating th e P yth on interpreter and devel


opm ent environm ent, l
aying a sol
id

foundationforl
anguage'ssyntax, h istoricalcontext, and th e distinctionsbetweenPyth on2 . xand

3 . x versions. A crucialcomponentof programming with Pyth on invol


ves th e util
iz ation of

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.

Significantemph asish asbeenpl


aced oncore programmingconceptssuch asconditional
s, l
oops,

functions, and modul


es. O bject- O riented P rogram m ing ( O O P ) principl
es aboutdecl
aring

cl
asses, creatingobjects, impl
ementinginh eritance, and customiz ingobjectbeh aviorth rough th e

use ofmagicmeth odsh asbeendiscussed. T h e curricul


um coversth e integrationofPyth onwith

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

1 . 1 .1 Pyth onK eywords 7 - 8

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

1 . 2 .1 Pyth onDataT ypes 1 1

2 . 3 .1 Pyth onF unction 3 1

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/

h ttps: / / www. interviewbit. com/ bl


og/ difference- between- pyth on- 2 - and- 3 /

h ttps: / / www. mygreatl


earning. com/ bl
og/ pyth on- 2 - vs- pyth on- 3 /

h ttps: / / www. geeksforgeeks. org/ pyth on- features/ 4 4


h ttps: / / www. sch ol
arh at. com/ tutorial
/ pyth on/ th e- basic- syntax- of- pyth on

h ttps: / / www. geeksforgeeks. org/ pyth on- data- types/

h ttps: / / www. geeksforgeeks. org/ conditional


- statements- in- pyth on/

h ttps: / / www. geeksforgeeks. org/ l


oops- in- pyth on/

h ttps: / / www. geeksforgeeks. org/ pyth on- oops- concepts/

h ttps: / / www. geeksforgeeks. org/ introduction- to- sql


ite/

h ttps: / / www. geeksforgeeks. org/ pyth on- functions/


PR O G R A M M IN G W IT H PY T H O N

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?

Interpretersare th e computerprogram th atwil


lconvertth e source code oranh igh l
evel
l
anguage into intermediate code ( mach ine l
evell
anguage) . Itisal
so cal
led transl
atorin
programmingterminol
ogy. Interpretersexecuteseach l
ine ofstatementssl
owl
y. T h isprocess

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 . 2 . 2 H ow interpretersfunctioninP yth on?

Pyth oninterpreteriswritteninC programmingl


anguage aswe al
lknow th atC is
considered asmoth erofal
lprogrammingl
anguages, Pyth oninterpretercal
led “ C Pyth on”.
Initial
ly insource code anal
ysis, Pyth ongetsource and ch eck forsome Indentationrul
e and
ch eck forerrors. ifth ere are any errorsPyth onstopsitsexecutionand make to modify to prevent
errors. T h isprocessiscal
led L exicalanal
ysisinpyth onwh ich statesth atdividingth e source
code into l
istofindividualtokens. InB yte code generation, once th e pyth oninterpreterreceives
th e tokens, itgeneratesA ST ( A bstractStructure tree) wh ich covertsto byte code and th enbyte
code canbe saved in( . py) extension. A tl
ast, by usingPyth onV irtualM ach ine, interpreterl
oads
th e mach ine l
anguage and PV M convertsininto 0 sand 1 swh ich printsth e resul
ts.

1 . 3 P Y T H O N V ER SIO N S

T h ere were avariety ofreasonsasto wh y th ere were differentversionsofPyth onavail


abl
e. F irstl
y, a
l
otofindustry code h ad beenal
ready writteninPyth on2 , and th erefore, compl
etel
y migratingfrom
Pyth on2 to Pyth on3 woul
d h ave turned outto be avery time- consumingand difficul
tjob. M oreover,
inorderto work with configurationmanagementtool
slike PuppetorA nsibl
e, knowl
edge ofboth
Pyth on2 and Pyth on3 wasrequired. H owever, overth e course oftime, Pyth on3 h asbeendevel
oped in
away to issuitabl
e forabroad variety offiel
dsl
ike webdevel
opment, datascience, anal
yticsscripting,
etc. Pyth on3 h asal
otofrich l
ibrariesand caneasil
y be integrated with oth erl
anguages. T h erefore, th e
need forboth versionsofPyth oncanbe easil
y understood. Inth e end, effortswere made to make
Pyth on3 supportal
otofmajorfunctional
itieswh ich Pyth on2 offered, and in2 0 2 0 , Pyth on2 saw its
demise.

1 . 3 . 1 P yth on2

Pyth on2 . 0 wasintroduced to th e tech worl


d inth e year2 0 0 0 . C reated by th e B eO pen
Pyth onL absteam, th e purpose ofth e introductionofPyth on2 wasto make programming
simpl
e and easy to l
earnforth e commonmasses. Pyth on2 wassuccessfulinimpl
ementingth e
tech nicaldetail
softh e Pyth onEnh ancementProposal( PEP) . H owever, afterth e introductionof
DEPA R T M EN T O F C SE, M B SC ET 2
PR O G R A M M IN G W IT H PY T H O N
Pyth on3 , Pyth on2 coul
d notfind al
otofitsusage inth e tech worl
d and th e year2 0 2 0 marked
th e end ofPyth on2 ’ sl
egacy with Pyth on2 . 7 beingitsl
atestversion.

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 . 3 . 3 Difference inP yth on2 & 3

B ased onth e fol


lowingparameters, th e differencesbetweenPyth on2 and Pyth on3 can
easil
y be made out. T h ey are asfol
lows:

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 .

2 . PrintK eywords: InPyth on2 , printisastatementrath erth anafunction, onth e oth er


h and, inPyth on3 , printisconsidered to be afunctionand notastatement.

3 . Storage ofStrings: InPyth on2 , stringsare stored asA SC II by defaul


twh ereas, in
Pyth on3 , stringsare stored asU N IC O DE.

4 . DivisionofIntegers: InPyth on2 , th e divisionoftwo integersresul


ted inanintegral
val
ue. F orexampl
e, 9 / 2 yiel
ds4 inPyth on2 wh ereasth e divisionoftwo integersresul
tsina
fl
oating- pointval
ue inPyth on3 . F orexampl
e, 9 / 2 yiel
ds4 . 5 inPyth on3 .

5 . Exceptions: InPyth on2 , exceptionsare used to encl


ose th e notations, onth e oth er
h and, InPyth on3 , parenth esesare used to encl
ose th e exceptions.

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

7 . Iteration: InPyth on2 , th e xrange( ) functionh asbeendefined foriterationswh ereasin


Pyth on3 , to perform iterations, th e new R ange( ) functionisintroduced.

8 . Ease O fSyntax: T h e syntaxofPyth on2 ismore compl


icated ascompared to th e
syntaxofPyth on3 . Pyth on3 syntaxiseasy to understand.

9 . L ibraries: Pyth on3 isth e future, th erefore many devel


opersare now creatingl
ibraries
forth e use ofPyth on3 strictl
y. T h e l
ibrariescreated forPyth on2 are now notforwards-
compatibl
e. 2 . xl
ibrary may be ported to 3 . xbutitcanbe acompl
icated task. Itisnot
recommended forbeginners.

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

Inth issectionwe wil


lsee wh atare th e featuresofPyth onprogrammingl
anguage :

1. F ree and O penSource : Pyth onl


anguage isfreel
y avail
abl
e atth e officialwebsite. Since itis
open- source, th ismeansth atsource code isal
so avail
abl
e to th e publ
ic. So youcandownl
oad it, use it
aswel
lassh are it.

2. Easy to code : Pyth onisah igh - l


evelprogrammingl
anguage. Pyth onisvery easy to l
earnth e
l
anguage ascompared to oth erl
anguagesl
ike C , C # , Javascript, Java, etc. Itisvery easy to code inth e

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.

3. Easy to R ead : A syouwil


lsee, l
earningPyth onisquite simpl
e. A swasal
ready establ
ish ed,
Pyth on’ ssyntaxisreal
ly straigh tforward. T h e code bl
ock isdefined by th e indentationsrath erth anby
semicol
onsorbrackets.

4. O bject- O riented L anguage : O ne ofth e key featuresofPyth onisO bject- O riented


programming. Pyth onsupportsobject- oriented l
anguage and conceptsofcl
asses, objectencapsul
ation,
etc.

5. G U IProgrammingSupport: G raph icalU serinterfacescanbe made usingamodul


e such
asPyQ t5 , PyQ t4 , wxPyth on, orT k inPyth on. PyQ t5 isth e mostpopul
aroptionforcreatinggraph ical
appswith Pyth on.

6. H igh - L evelL anguage : Pyth onisah igh - l


evell
anguage. W h enwe write programsinPyth on,
we do notneed to rememberth e system arch itecture, nordo we need to manage th e memory.

7. L arge C ommunity Support: Pyth onh asgained popul


arity overth e years. O urquestionsare
constantl
y answered by th e enormousStackO verfl
ow community. T h ese websitesh ave al
ready
provided answersto many questionsaboutPyth on, so Pyth onuserscanconsul
tth em asneeded.

8. Easy to Debug: Excel


lentinformationformistake tracing. Y ouwil
lbe abl
e to quickl
y
identify and correctth e majority ofyourprogram’ sissuesonce youunderstand h ow
to interpret Pyth on’ serrortraces. Simpl
y by gl
ancingatth e code, youcandetermine wh atitis
designed to perform.

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.

10. Pyth onisanIntegrated l


anguage : Pyth onisal
so anIntegrated l
anguage because we can
easil
y integrate Pyth onwith oth erl
anguagesl
ike C , C + + , etc.

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

1 1 . Interpreted L anguage : Pyth onisanInterpreted L anguage because Pyth oncode isexecuted


l
ine by l
ine atatime. l
ike oth erl
anguagesC , C + + , Java, etc. th ere isno need to compil
e Pyth oncode
th ismakesiteasierto debugourcode. T h e source code ofPyth onisconverted into animmediate form
cal
led bytecode.

1 2 . L arge Standard L ibrary : Pyth onh asal


arge standard l
ibrary th atprovidesarich setof
modul
esand functionsso youdo noth ave to write yourowncode forevery singl
e th ing. T h ere are
many l
ibrariespresentinPyth onsuch asregul
arexpressions, unit- testing, webbrowsers, etc.

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.

14. F rontend and backend devel


opment: W ith anew projectpy script, youcanrunand write
Pyth oncodesinH T M L with th e h el
pofsome simpl
e tags< py- script> , < py- env> , etc. T h iswil
lh el
p
youdo frontend devel
opmentwork inPyth onl
ike javascript. B ackend isth e strongforte ofPyth onit’ s
extensivel
y used forth iswork cause ofitsframeworksl
ike Django and F l
ask.

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.

H ere are namingconventionsforidentifiersinPyth on:

1. Inth e Pyth onprogrammingl


anguage th e cl
assnamesstartwith anuppercase l
etterand
al
lth e oth eridentifiersstartwith al
owercase l
etter.

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

return T rue try

wh il
e with yiel
d

1 . 5 . 2 P yth onL inesand Indentation

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.

F ig2 . 1 : P yth onDataT ypes

2 . 2 W h atare P yth onDataT ypes?

A datatype inPyth onisacl


assificationofspecifictypesofdataby acertainval
ue orcertaintypesof
math ematicalorl
ogicaloperations. T h e way th atdataitemsare categoriz ed orcl
assified isknownas
th eirdatatype. Itstandsforth e type ofval
ue th atindicatesth e typesofoperationsth atcanbe carried
outonaspecificsetofdata. Inth isprogramming, pyth onvariabl
esare instances( objects) of
th ese pyth oncl
asses, and datatypesare trul
y cl
assesbecause everyth ingisanobject.

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

2 . 3 N um ericDataT ypesinP yth on

T h e numericdatatype inPyth onrepresentsth e datath ath asanumericval


ue. A numericval
ue canbe
aninteger, afl
oatingnumber, orevenacompl
exnumber. T h ese val
uesare defined asPyth on
int , Pyth onfl
oat , and Pyth oncompl
ex cl
assesinPyth on. T h e variousnumericdatatypesinpyth on
are asfol
lows:

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.

a= 5 print( " T ype ofa: " , type( a) )


b= 5 . 0 print( " \nT ype ofb: " , type( b) )
c= 2 + 4 jprint( " \nT ype ofc: " , type( c) )

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

2 . 4 Sequence DataT ypesinP yth on

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

Strings inPyth onare arraysofbytesrepresentingU nicode ch aracters. A stringisa


col
lectionofone ormore ch aractersputinasingl
e quote, doubl
e- quote, ortripl
e- quote. In
Pyth on, th ere isno ch aracterdatatype Pyth on, ach aracterisastringofl
ength one. Itis
represented by strcl
ass.

1. C reatingStrings: StringsinPyth oncanbe created usingsingl


e quotes, doubl
e quotes,
oreventripl
e quotes.
Exampl
e: T h isPyth oncode sh owcasesvariousstringcreationmeth ods. Itusessingl
e
quotes, doubl
e quotes, and tripl
e quotesto create stringswith differentcontentand incl
udesa
mul
til
ine string. T h e code al
so demonstratesprintingth e stringsand ch eckingth eirdatatypes.

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

Stringcanbe accessed by usingth e meth od ofIndexing. N egative Indexing al


lowsnegative
addressreferencesto accessch aractersfrom th e back ofth e String, e. g. - 1 refersto th e l
ast
ch aracter, - 2 refersto th e second l
astch aracter, and so on.

e: T h isPyth oncode demonstratesh ow to work with astringnamed ‘String1 ′ . It


Exampl
initial
iz esth e stringwith “ G eeksF orG eeks”and printsit. Itth ensh owcasesh ow to accessth e
firstch aracter( “ G ”) usinganindexof0 and th e l
astch aracter( “ s”) usinganegative indexof
-1 .

String1 = " G eeksF orG eeks"


print( " InitialString: " )
print( String1 )
print( " \nF irstch aracterofStringis: " )
print( String1 [0 ])
print( " \nL astch aracterofStringis: " )
print( String1 [- 1 ])

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

L ists are justl


ike arrays, decl
ared inoth erl
anguageswh ich isanordered col
lectionof
data. Itisvery fl
exibl
e asth e itemsinal
istdo notneed to be ofth e same type.
1. C reatingaL istinPyth on: L istsinPyth oncanbe created by justpl
acingth e sequence
inside th e square brackets[].

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.

L ist= []print( " Initialbl


ank L ist: " )
print( L ist)
L ist= ['G eeksF orG eeks']
print( " \nL istwith th e use ofString: " )
print( L ist)
L ist= [" G eeks" , " F or" , " G eeks" ]
print( " \nL istcontainingmul
tipl
e val
ues: " )
print( L ist[0 ])
print( L ist[2 ])
L ist= [['G eeks', 'F or'], ['G eeks']]
print( " \nM ul
ti- DimensionalL ist: " )
print( L ist)

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']]

2. Pyth onA ccessL istItems: Inorderto accessth e l


istitemsreferto th e indexnumber.
U se th e indexoperator[]to accessanitem inal
ist. InPyth on, negative sequence indexes
representpositionsfrom th e end ofth e array. Instead ofh avingto compute th e offsetasin
L ist[l
en( L ist) - 3 ], itisenough to justwrite L ist[- 3 ]. N egative indexingmeansbeginningfrom th e
end, - 1 refersto th e l
astitem, - 2 refersto th e second- l
astitem, etc.
Exampl
e:
L ist= [" G eeks" , " F or" , " G eeks" ]
print( " A ccessingel
ementfrom th e l
ist" )
print( L ist[0 ])
print( L ist[2 ])
print( " A ccessingel
ementusingnegative indexing" )
print( L ist[- 1 ])
print( L ist[- 3 ])

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

Pyth onDatatype with one ofth e two buil


t- inval
ues, T rue orF al
se. B ool
eanobjectsth at
are equalto T rue are truth y ( true) , and th ose equalto F al
se are fal
sy ( fal
se) . H owevernon-
B ool
eanobjectscanbe eval
uated inaB ool
eancontextaswel
land determined to be true orfal
se.
Itisdenoted by th e cl
assbool
.

N ote – T rue and F al


se with capital‘T ’ and ‘F ’ are val
id bool
eansoth erwise pyth onwil
l
th row anerror.

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.

print( type( T rue) )


print( type( F al
se) )
print( type( true) )

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

InPyth onDataT ypes, aSet isanunordered col


lectionofdatatypesth atisiterabl
e,
mutabl
e, and h asno dupl
icate el
ements. T h e orderofel
ementsinasetisundefined th ough it
may consistofvariousel
ements.

1. C reate aSetinPyth on: Setscanbe created by usingth e buil


t- inset( ) functionwith
aniterabl
e objectorasequence by pl
acingth e sequence inside curl
y braces, separated by
a‘comma’ . T h e type ofel
ementsinasetneed notbe th e same, variousmixed- updatatype
val
uescanal
so be passed to th e set.

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'}

2. A ccessSetItems: Setitemscannotbe accessed by referringto anindex, since sets


are unordered th e itemsh ave no index. B utyoucanl
oopth rough th e setitemsusingaforl
oop,
orask ifaspecified val
ue ispresentinaset, by usingth e inth e keyword.

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

set1 = set( [" G eeks" , " F or" , " G eeks" ])


print( " \nInitialset" )
print( set1 )
print( " \nEl
ementsofset: " )
fori inset1 :
print( i, end= " " )
print( " G eeks" inset1 )

O utput:
Initialset:
{ 'G eeks', 'F or'}
El
ementsofset:
G eeksF or
T rue

2 . 4 . 6 Dictionary DataT ype inP yth on

A dictionary inPyth onisanunordered col


lectionofdataval
ues, used to store data
val
uesl
ike amap, unl
ike oth erPyth onDataT ypesth ath ol
d onl
y asingl
e val
ue asanel
ement, a
Dictionary h ol
dsakey: val
ue pair. K ey- val
ue isprovided inth e dictionary to make itmore
optimiz ed. Each key- val
ue pairinaDictionary isseparated by acol
on: , wh ereaseach key is
separated by a‘comma’ .

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'}

2. A ccessingK ey- val


ue inDictionary : Inorderto accessth e itemsofadictionary refer
to itskey name. K ey canbe used inside square brackets. T h ere isal
so ameth od cal
led get( ) th at
wil
lal
so h el
pinaccessingth e el
ementfrom adictionary.

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’ .

Dict= { 1 : 'G eeks', 'name': 'F or', 3 : 'G eeks'}


print( " A ccessingael
ementusingkey: " )
print( Dict['name'])
print( " A ccessingael
ementusingget: " )
print( Dict. get( 3 ) )

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

C onditionalStatementsare statementsinPyth onth atprovide ach oice forth e controlfl


ow based ona
condition. Itmeansth atth e controlfl
ow ofth e Pyth onprogram wil
lbe decided based onth e outcome
ofth e condition.

3 . 2 . 1 IfC onditionalStatem entinP yth on


Ifth e simpl
e code ofbl
ock isto be performed ifth e conditionh ol
dsth enth e ifstatement
isused. H ere th e conditionmentioned h ol
dsth enth e code ofth e bl
ock runsoth erwise not.

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

3 . 2 . 5 T ernary ExpressionC onditionalStatem entsinP yth on


T h e Pyth onternary Expressiondeterminesifaconditionistrue orfal
se and th enreturns
th e appropriate val
ue inaccordance with th e resul
t. T h e ternary Expressionisusefulincases
wh ere we need to assignaval
ue to avariabl
e based onasimpl
e condition, and we wantto keep
ourcode more concise — al
linjustone l
ine ofcode.

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

3 . 4 P yth onF unctions

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

Some B enefitsofU singF unctions:


1. Increase C ode R eadabil
ity
2. Increase C ode R eusabil
ity

Pyth onF unctionDecl


aration:
T h e syntaxto decl
are afunctionis

F ig3 . 1 : P yth onF unction

3 . 4 . 1 C reatingaF unctioninP yth on


W e candefine afunctioninPyth on, usingth e defkeyword. W e canadd any type of
functional
itiesand propertiesto itaswe require. B y th e fol
lowingexampl
e, we canunderstand
h ow to write afunctioninPyth on. Inth isway we cancreate Pyth onfunctiondefinitionby using
defkeyword.

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:

defadd( num1 : int, num2 : int) - > int:


num3 = num1 + num2
returnnum3

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 bjectO riented ProgrammingisafundamentalconceptinPyth on, empoweringdevel


opersto buil
d
modul
ar, maintainabl
e, and scal
abl
e appl
ications. B y understandingth e core O O P principl
es— cl
asses,
objects, inh eritance, encapsul
ation, pol
ymorph ism, and abstraction— programmerscanl
everage th e ful
l
potentialofPyth on’ sO O P capabil
itiesto designel
egantand efficientsol
utionsto compl
exprobl
ems.
O bject- oriented Programming( O O Ps) isaprogrammingparadigm th atusesobjectsand cl
assesin
programming. Itaimsto impl
ementreal
- worl
d entitiesl
ike inh eritance, pol
ymorph isms, encapsul
ation,
etc. inth e programming. T h e mainconceptofobject- oriented Programming( O O Ps) oroopsconceptsin
Pyth onisto bind th e dataand th e functionsth atwork togeth erasasingl
e unitso th atno oth erpartof
th e code canaccessth isdata.

O O P C oncepts:

Cl
assinPyth on

O bjectsinPyth on

Pol
ymorph ism inPyth on

Encapsul
ationinPyth on

Inh eritance inPyth 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

Some pointsonPyth oncl


ass:

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

4 . 3 P yth onO bjects

Inobjectoriented programmingPyth on, T h e objectisanentity th ath asastate and beh aviorassociated


with it. Itmay be any real
- worl
d objectl
ike amouse, keyboard, ch air, tabl
e, pen, etc. Integers, strings,
fl
oating- pointnumbers, evenarrays, and dictionaries, are al
lobjects. M ore specifical
ly, any singl
e
integerorany singl
e stringisanobject. T h e number1 2 isanobject, th e string“ H el
lo, worl
d”isan
object, al
istisanobjectth atcanh ol
d oth erobjects, and so on.

A nobjectconsistsof:

State: Itisrepresented by th e attributesofanobject. Ital


so refl
ectsth e propertiesofanobject.

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.

Identity: Itgivesaunique name to anobjectand enabl


esone objectto interactwith oth erobjects.

T o understand th e state, beh avior, and identity l


etustake th e exampl
e ofth e cl
assdog.

T h e identity canbe considered asth e name ofth e dog.

State orA ttributescanbe considered asth e breed, age, orcol


orofth e dog.

T h e beh aviorcanbe considered asto wh eth erth e dogiseatingorsl


eeping.

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.

4 . 5 T h e P yth on__init__M eth od

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

attr1 = " mammal


"

# Instance attribute

def__init__( sel
f, name) :

sel
f. name = name

# Drivercode

# O bjectinstantiation

R odger= Dog( " R odger" )

T ommy = Dog( " T ommy" )

# A ccessingcl
assattributes

print( " R odgerisa{ }" . format( R odger. __cl


ass__. attr1 ) )

print( " T ommy isal


so a{ }" . format( T ommy. __cl
ass__. attr1 ) )

# A ccessinginstance attributes

print( " M y name is{ }" . format( R odger. name) )

print( " M y name is{ }" . format( T ommy. name) )

O utput

R odgerisamammal

T ommy isal
so amammal

M y name isR odger

M y name isT ommy


DEPA R T M EN T O F C SE, M B SC ET 3 6
PR O G R A M M IN G W IT H PY T H O N

4 . 6 P yth onInh eritance

InPyth onobjectoriented Programming, Inh eritance isth e capabil


ity ofone cl
assto derive orinh eritth e
propertiesfrom anoth ercl
ass. T h e cl
assth atderivespropertiesiscal
led th e derived cl
assorch il
d cl
ass
and th e cl
assfrom wh ich th e propertiesare beingderived iscal
led th e base cl
assorparentcl
ass. T h e
benefitsofinh eritance are:

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.

Itistransitive innature, wh ich meansth atifcl


assB inh eritsfrom anoth ercl
assA , th enal
lth e
subcl
assesofB woul
d automatical
ly inh eritfrom cl
assA .

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.

H ierarch icalInh eritance: H ierarch ical


-levelinh eritance enabl
esmore th anone derived cl
assto inh erit
propertiesfrom aparentcl
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

Inobjectoriented ProgrammingPyth on, Pol


ymorph ism simpl
y meansh avingmany forms. F orexampl
e,
we need to determine ifth e givenspeciesofbirdsfl
y ornot, usingpol
ymorph ism we cando th isusinga
singl
e function.

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) :

print( " T h ere are many typesofbirds. " )

deffl
igh t( sel
f) :

print( " M ostofth e birdscanfl


y butsome cannot. " )

cl
asssparrow( B ird) :

deffl
igh t( sel
f) :

print( " Sparrowscanfl


y. " )

cl
assostrich ( B ird) :

deffl
igh t( sel
f) :

print( " O strich escannotfl


y. " )

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( )

obj_ost. intro( ) obj_ost. fl


igh t( )

O utput

T h ere are many typesofbirds.

M ostofth e birdscanfl
y butsome cannot.

T h ere are many typesofbirds.

Sparrowscanfl
y.

T h ere are many typesofbirds.

O strich escannotfl
y.

4 . 8 P yth onEncapsul
ation

InPyth onobjectoriented programming, Encapsul ationisone ofth e fundamentalconceptsinobject-


oriented programming( O O P) . Itdescribesth e ideaofwrappingdataand th e meth odsth atwork ondata
with inone unit. T h isputsrestrictionsonaccessingvariabl esand meth odsdirectl y and canpreventth e
accidentalmodificationofdata. T o preventaccidentalch ange, anobject’ svariabl e canonly be ch anged
by anobject’ smeth od. T h ose typesofvariabl esare knownasprivate variabl es. A cl assisanexampl e
ofencapsul ationasitencapsul atesallth e datath atismemberfunctions, variabl es, etc.

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

Pyth onSQ L ite3 modul


e isused to integrate th e SQ L ite database with Pyth on. Itisastandardiz ed
Pyth onDB IA PI2 . 0 and providesastraigh tforward and simpl
e- to- use interface forinteractingwith
SQ L ite databases. T h ere isno need to instal
lth ismodul
e separatel
y asitcomesal
ongwith Pyth onafter
th e 2 . 5 xversion.

Pyth oncomeswith buil


t- insupportforSQ L ite th rough th e sql
ite3 modul
e, wh ich al
lowsyouto interact
with anSQ L ite database directl
y from Pyth oncode. T h ismakesitanexcel
lentch oice forappl
ications
th atrequire al
igh tweigh tdatabase with outth e overh ead ofaful
ldatabase managementsystem.

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 :

C h aracteristicsofSQ L ite Database :

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

C onnectingto th e SQ L ite Database canbe establ


ish ed usingth e connect( ) meth od, passingth e name of
th e database to be accessed asaparameter. Ifth atdatabase doesnotexist, th enit’ l
lbe created.

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 SQ L query to be executed canbe writteninform ofastring, and th enexecuted by cal


ling
th e execute( ) meth od onth e cursorobject. T h en, th e resul
tcanbe fetch ed from th e serverby using
th e fetch al
l( ) meth od, wh ich inth iscase, isth e SQ L ite V ersionN umber.

query = 'SQ L query; '


cursor. execute( query)
resul
t= cursor. fetch al
l()
print( 'SQ L ite V ersionis{ }'. format( resul
t) )

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:

# C onnectto DB and create acursor


sqliteC onnection= sql ite3 . connect( 'sql
. db')
cursor= sql iteC onnection. cursor( )
print( 'DB Init')

# W rite aquery and execute itwith cursor


query = 'selectsql ite_version( ) ; '
cursor. execute( query)

# F etch and outputresul t


result= cursor. fetch all()
print( 'SQ L ite V ersionis{ }'. format( resul
t) )

# Cl ose th e cursor
cursor. cl
ose( )

# H andl e errors
exceptsql ite3 . Erroraserror:
print( 'Erroroccurred - ', error)

# Cl ose DB C onnectionirrespective ofsuccess


# orfail ure
finall
y:

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

SQ L ite isah igh l


y efficient, serverl
ess, and sel
f- contained SQ L database engine th atstandsout
foritssimpl
icity and ease ofintegration. Designed to be embedded with in
DEPA R T M EN T O F C SE, M B SC ET 4 2
PR O G R A M M IN G W IT H PY T H O N
appl
ications, SQ L ite el
iminatesth e need forseparate database serverprocessesand compl
ex
configurations.

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.

2. SQ L ite isanin- processl


ibrary th atimpl
ementsasel
f- contained, serverl
ess, z ero-
configuration, transactionalSQ L database engine. Itisapopul
arch oice asanembedded database
forl
ocal
/ cl
ientstorage inappl
icationsoftware such aswebbrowsers. Itisal
so used inmany oth er
appl
icationsth atneed al
igh tweigh t, embedded database.

3. SQ L ite isA C ID- compl


iantand impl
ementsmostofth e SQ L standards, usingadynamical
ly and
weakl
y typed SQ L syntaxth atdoesnotguarantee domainintegrity.

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

T h ere are severalreasonswh y youmigh tch oose to use SQ L ite inyourproject:

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.

3. L igh tweigh t: SQ L ite isavery l


igh tweigh tdatabase engine, with asmal
llibrary siz e ( typical
lyl
ess
th an1 M B ) . T h ismakesitwel
l- suited foruse inappl
icationswh ere th e database isembedded directl
y
into th e appl
icationbinary, such asmobil
e apps.

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.

C R EA T EIN DEX : createsanew indexonatabl


e.

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

ofDM L statementsinSQ L ite are:

IN SER T IN T O : insertsanew row into atabl


e.

U PDA T E: updatesth e datainone ormore rowsofatabl


e.

DEL ET EF R O M : del
etesone ormore rowsfrom atabl
e

DQ L ( DataQ uery L anguage) isused to retrieve datafrom th e database. Some exampl


esofDQ L

statementsinSQ L ite are:


DEPA R T M EN T O F C SE, M B SC ET 4 4
PR O G R A M M IN G W IT H PY T H O N
SEL EC T : retrievesdatafrom one ormore tabl
esinth e database.

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

Y our reason for


Datafiel
d identifier Datatype Exam pl
e using th is
datatype
N ames may
contain l etters
pl
ayer_name String V iratK oh l
i
and any oth er
ch aracters.
C ountry name
may contain
country String India
letters and any
oth erch aracters.
fours Integer 1 2 0
N umber of
N umber_of_match es integer 3 3 9 match es contain
integerval
ue
india= [" virat
koh l i" , " " m. s. dh oni" ,
A ch angeabl e
" yuvraj singh " , " roh it
T eam L ist collection of
sh arma" , " B h uvnesh w
playernames.
ar
kumar" , " " a. rah ane" ]
p1 = { 'name': 'V irat
K oh l i', 'runs': 2 5 2 3 8 , T h is is a
'4 ( fours) ': 1 2 0 , '6 ( sixes col lection of
pl
ayer_stats Dictionary
) ': 8 0 , 'bal ls': 1 1 9 , relevant pl ayer
'rol e': 'bat', stats.
'fiel d': 0 , ’ 1 0 0 ’ : 8 3 }
R un rate is th e
runs required per
run_rate Fl oat 3 .2 delivery. T h is
canh ave decimal
values.

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

# functionsused forscore cal


cul
ation

defbatscore( x) :

runs= x['runs']

strike_rate = runs/ x['bal


ls']

score = runs/ / 2 + ( 5 ifruns> = 5 0 el


se 0 ) + ( 1 0 ifruns> = 1 0 0 el
se 0 ) + ( 2 ifstrike_rate > = 8 0 / 1 0 0

and strike_rate < = 1 el


se 0 ) + ( 4 ifstrike_rate > 1 el
se 0 ) + x['4 ']+ x['6 ']* 2

returnscore

return{ 'name': x['name'], 'batscore': score}

defbowl
score( x) :

wkts= x['wkts']

economy_rate = x['runs']/ x['overs']

fiel
ds= x['fiel
d']

score = 1 0 * wkts+ ( 1 0 * fiel


dsiffiel
ds> = 1 el
se 0 ) + ( 5 ifwkts> = 3 el
se 0 ) + ( 1 0 ifwkts> = 5 el
se 0 ) +

( 4 ifeconomy_rate> = 3 . 5 and economy_rate< = 4 . 5 el


se 0 ) + ( 7 ifeconomy_rate> = 2 and

economy_rate< 3 . 5 el
se 0 ) + ( 1 0 ifeconomy_rate< 2 el
se 0 )

returnscore

return{ 'name': x['name'], 'bowl


score': score}

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

p1 = { 'name': 'V iratK oh l


i', 'rol
e': 'bat', 'runs': 1 1 2 , '4 ': 1 0 , '6 ': 0 , 'bal
ls': 1 1 9 , 'fiel
d': 0 }

p2 = { 'name': 'duPl
essis', 'rol
e': 'bat', 'runs': 1 2 0 , '4 ': 1 1 , '6 ': 2 , 'bal
ls': 1 1 2 , 'fiel
d': 0 }

p3 = { 'name': 'B h uvnesh warK umar', 'rol


e': 'bowl
', 'wkts': 1 , 'overs': 1 0 , 'runs': 7 1 , 'fiel
d': 1 }

p4 = { 'name': 'Y uz vendraC h ah al


', 'rol
e': 'bowl
', 'wkts': 2 , 'overs': 1 0 , 'runs': 4 5 , '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

print( " 'name': { }, 'batscore': { }" . format( 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) )

max_scorer= max( scores, key= scores. get)

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:

" " " B O O k detaail


s. " " "

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

defget_auth or( sel


f) :

returnsel
f. auth or

defset_auth or( sel


f, b) :

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) :

" " " E- B O O K Detais" " "

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

a= input( " Enterth e titl


e ofth e book " )

b= input( " Enterth e auth orofth e book " )

c= input( " Enterth e publ


ish erofbook " )

d= int( input( " Enterth e price ofth e book " ) )

e= int( input( " Enterth e totalnumberofbookssol


d" ) )

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( )

print( " T itl


e is{ } \nPubl
ish eris{ } \nA uth oris{ } \nPrice was{ } \nT otalsol
d { } \nR oyal
ty is{ }

\n" . format( x. titl


e, x. publ
ish er, x. auth or, x. price, x. quan, z ) )

iff= = 2 :

print( " b" )

g= input( " Enterth e formatofebook" )

z = y. royal
ty( )

y. set_format( g)

print( " T itl


e is{ } \nPubl
ish eris{ } \nA uth oris{ } \nPrice was{ } \nT otalsol
d { } \nF ormatis{ } \n

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

h ttps: / / www. geeksforgeeks. org/


h ttps: / / www. geeksforgeeks. org/ pyth on- data- types/
h ttps: / / www. geeksforgeeks. org/ loops- in- pyth on/
h ttps: / / www. geeksforgeeks. org/ pyth on- oops- concepts/
h ttps: / / www. geeksforgeeks. org/ introduction- to- sql ite/
h ttps: / / www. geeksforgeeks. org/ conditional - statements- in- pyth on/

DEPA R T M EN T O F C SE, M B SC ET 5 9

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy