introduction to python unit notes .pdf

Samyuktha481974 38 views 206 slides Mar 02, 2025
Slide 1
Slide 1 of 206
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163
Slide 164
164
Slide 165
165
Slide 166
166
Slide 167
167
Slide 168
168
Slide 169
169
Slide 170
170
Slide 171
171
Slide 172
172
Slide 173
173
Slide 174
174
Slide 175
175
Slide 176
176
Slide 177
177
Slide 178
178
Slide 179
179
Slide 180
180
Slide 181
181
Slide 182
182
Slide 183
183
Slide 184
184
Slide 185
185
Slide 186
186
Slide 187
187
Slide 188
188
Slide 189
189
Slide 190
190
Slide 191
191
Slide 192
192
Slide 193
193
Slide 194
194
Slide 195
195
Slide 196
196
Slide 197
197
Slide 198
198
Slide 199
199
Slide 200
200
Slide 201
201
Slide 202
202
Slide 203
203
Slide 204
204
Slide 205
205
Slide 206
206

About This Presentation

notes for python programming. for beginners


Slide Content

BCA
IN24C04
BATCH 2024
(Semester 2)
73 Hrs

BCA
A.MarkLutzLearningpython(UnitI-III)O’Reilly
Publication2013,5thEdition.
B.AllenB.Downey ThinkPython:HowtoThink
likeaComputerScientist(UnitIV-V)O’Reilly
Publishers,2016,2ndEdition.
C.KapilKapoorIndianKnowledgesystemsIndian
InstituteofAdvancedstudy 2005,1stEdition.
CA: 25
ESE: 75
TOTAL: 100
DEC-MAR 2025 2Dr. Reshmi. S I BCA B

BCA
Course Code : IN24C04
Credits : 3
DEC-MAR 2025 3Dr. Reshmi. S I BCA B
A.E.Balagurusamy ProblemSolvingandPython
ProgrammingMcGraw-Hill2017,1stEdition.
B.GuidovanRossumandFredL.DrakeJr AnIntroduction
toPython–RevisedandupdatedforPython3.2 Python
SoftwareFoundation,NetworkTheoryLtd2011, 1st
Edition.
C.WesleyJChunCorePythonApplicationsProgramming
PrenticeHall2012,3rdEdition.

BCA
SYLLABUS FOR UNIT 1 [10 Hrs]
Introduction:Whydopeopleusepython-
Pythonascriptinglanguage-UsersofPython-
NeedofPython-Python’sTechnicalStrengths-
HowPythonrunsprograms:Introducingthe
PythonInterpreter-ProgramExecution-
Execution Model Variation: Python
ImplementationAlternatives.
DEC-MAR 20254 Dr. Reshmi. S I BCA B

BCA
5
INTRODUCTION
DEC-MAR 2025
Dr. Reshmi. S I BCA B

BCA
•Pythonisahigh-level,interpreted,general-
purpose,dynamicprogramminglanguage.
•Pythonwasconceivedinthelate1980sand
itsusagebeganfromDecember1989.
DEC-MAR 2025
6Dr. Reshmi. S I BCA B

BCA
•Itisawidelyusedprogramminglanguage.
•Pythonpossessesapropertyofcodetermed
reusability.
•Thesyntaxofpythonprogramscanexpress
conceptsinfewerlinesascomparedtoprogramsin
C,C++andJAVA.
•Pythoncanbeusedinmultipleprogrammingstyles,
includingobject-oriented,functionalprogramming,
proceduralprogrammingandimperativestyles.
•Pythonsupportsautomaticmemorymanagement.
•Pythonisfreeandopen-sourcesoftware.
DEC-MAR 2025 7Dr. Reshmi. S I BCA B

BCA
•ItwasinitiallydesignedbyGuidovanRossum
in1991anddevelopedbyPythonSoftware
Foundation.
•Pythonisaprogramminglanguagethatlets
youworkquicklyandintegratesystemsmore
efficiently.
•TherearetwomajorPythonversions-Python
2andPython3.Botharequitedifferent.
DEC-MAR 2025
8Dr. Reshmi. S I BCA B

BCA
WhatisPython?
•Pythonisapopularprogramminglanguage.It
wascreatedbyGuidovanRossum,and
releasedin1991.
•Itisusedfor:
–webdevelopment(server-side),
–softwaredevelopment,
–mathematics,
–systemscripting.
DEC-MAR 2025 9Dr. Reshmi. S I BCA B

BCA
WhatcanPythondo?
Itcanbeusedonaservertocreateweb
applications.
Itcanbeusedalongsidesoftwaretocreate
workflows.
Itcanconnecttodatabasesystems.
Itcanalsoreadandmodifyfiles.
Itcanbeusedtohandlebigdataandperform
complexmathematics.
Itcanbeusedforrapidprototyping,orfor
production-readysoftwaredevelopment.
DEC-MAR
2025
10Dr. Reshmi. S I BCA B

BCA
WhyPython?
Pythonworksondifferentplatforms(Windows,
Mac,Linux,RaspberryPi,etc).
PythonhasasimplesyntaxsimilartotheEnglish
language.
Pythonhassyntaxthatallowsdeveloperstowrite
programswithfewerlinesthansomeother
programminglanguages.
Pythonrunsonaninterpretersystem,meaning
thatcodecanbeexecutedassoonasitiswritten.
Thismeansthatprototypingcanbeveryquick.
Pythoncanbetreatedinaproceduralway,an
object-orientatedwayorafunctionalway.
DEC-MAR 2025 11Dr. Reshmi. S I BCA B

BCA
Whydopeopleusepython?
PeopleusePythonforawiderangeof
applicationsduetoitsversatility,easeofuse,and
vastecosystem.
Python’sversatility,simplicity,andvast
ecosystemmakeitanidealchoiceforbeginners,
professionals,andcompaniesalike.
Whetherit'sbuildingawebapp,analyzingdata,
ordevelopingmachinelearningmodels,Python
offersastraightforwardandpowerfulsolution.
DEC-MAR 2025 12Dr. Reshmi. S I BCA B

BCA
EasytoLearnandUse:
PythonhasasimplesyntaxthatresemblesEnglish,
makingitbeginner-friendly.
Minimaluseofcomplexconstructsallowsforfaster
learningandimplementation.
DEC-MAR 2025 13Dr. Reshmi. S I BCA B
print("Hello, World!")

BCA
Versatility:
Pythoncanbeusedforvariouspurposes,including:
WebDevelopment:FrameworkslikeDjango,Flask.
DataScienceandMachineLearning:Librarieslike
Pandas,NumPy,TensorFlow.
Automation:Scriptingrepetitivetasks.
GameDevelopment:LibrarieslikePygame.
EmbeddedSystems:Usedinmicrocontrollers(e.g.,
RaspberryPi).
DEC-MAR 2025 14Dr. Reshmi. S I BCA B

BCA
ExtensiveLibrariesandFrameworks:
Pythonhasarichcollectionofpre-builtlibrariesfor
virtuallyanydomain.
Examples:
DataAnalysis:Pandas,NumPy.
MachineLearning:TensorFlow,Scikit-learn.
WebScraping:BeautifulSoup,Scrapy.
Visualization:Matplotlib,Seaborn.
DEC-MAR 2025 15Dr. Reshmi. S I BCA B

BCA
Cross-PlatformCompatibility:
Pythonrunsonvariousplatforms,includingWindows,
macOS,andLinux.
Writecodeonceandrunitanywherewithoutsignificant
modifications.
StrongCommunitySupport:
Avastandactivecommunityprovidesextensive
resources,tutorials,andsupport.
Availabilityofopen-sourcecontributionsandforumslike
StackOverflow.
DEC-MAR 2025 16Dr. Reshmi. S I BCA B

BCA
ProductivityandEfficiency:
Python’ssimplicityanddynamictypingmake
developmentfastercomparedtomanyother
programminglanguages.
Highproductivitymakesitsuitableforrapidprototyping.
ApplicationsinEmergingTechnologies:
DataScienceandAI:Pythonisthego-tolanguagefor
analyzingdata,buildingpredictivemodels,andtrainingAI
systems.
IoT(InternetofThings):Pythonisusedforprogramming
IoTdevicesandmanagingreal-timedata.
DEC-MAR 2025 17Dr. Reshmi. S I BCA B

BCA
Interoperability:
Pythoncanintegratewithotherlanguages(e.g.,C,C++,
Java)forspecificusecases,allowingdeveloperstousethe
besttoolforeachtask.
WhoUsesPython?
Companies:Google,Facebook,Instagram,Netflix,Spotify,
NASA,andmanymore.
Domains:Finance,healthcare,entertainment,education,
e-commerce,andmore.
DEC-MAR 2025 18Dr. Reshmi. S I BCA B

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B 19
PYTHON ORIGINS

BCA
WorkonPythonbeganinlate1989byGUIDOVAN
ROSSUM.
Itwaseventuallyreleasedforpublicdistributionin
early1991.
LikeC,C++,Lisp,JavaandPerl,Pythoncamefroma
researchbackgroundwheretheprogrammerwas
havingahardtimegettingthejobdonewiththe
existingtoolsathandandenvisionedanddevelopeda
betterway.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 20

BCA
ItwasnamedaftertheMontyPythoncomedy
group.
Pythonisahigh-level,interpretedlanguagethatwas
designedforcodereadabilityandeaseofuse.
Itisusedforawiderangeofapplications,including
webdevelopment,scientificcomputing,data
analysis,artificialintelligence,andmore.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 21

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B 22
PYTHON OVERVIEW and
FEATURES

BCA
Dr. Reshmi. S I BCA B 23DEC-MAR 2025

BCA
Thecodewritteninpythonisautomatically
compiledtobytecodeandexecuted.
Pythoncanbeusedasascriptinglanguage,asa
languageforimplementingwebapplicationsetc.
ExtendingpythonwithCorC++canhelpinthe
performanceofintensivetaskswherespeedof
executionisakeycriterion.
Pythonsupportsmanyfeaturessuchasnestedcode
blocks,functions,classes,modulesandpackages.
Pythonmakesuseofanobject-oriented
programmingapproach.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 24

BCA
Dr. Reshmi. S I BCA B 25
DEC-MAR 2025

BCA
FEATURESARE:
1.HighLevel
2.ObjectOriented
3.Scalable
4.Extensible
5.Portable
6.EasytoLearn
DEC-MAR 2025 Dr. Reshmi. S I BCA B 26
7.EasytoRead
8.EasytoMaintain
9.Robust
10.EffectiveasaRapid
PrototypingTool
11.AmemoryManager
12.InterpretedandByte-
Compiled

BCA
1.HighLevel:
•Pythonisanobject-oriented,high-level
programminglanguage.
•Object-orientedmeansthislanguageisbased
aroundobjects(suchasdata)ratherthan
functions,andhigh-levelmeansit'seasyfor
humanstounderstand.
•PythonLists(resizeablearrays)anddictionaries
(hashtables)arebuiltintothelanguage.
•Minimizesdevelopmenttimeandcodesize–
readablecode.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 27

BCA
2.ObjectOriented:
•InPython,object-orientedProgramming(OOPs)
isaprogrammingparadigmthatusesobjectsand
classesinprogramming.
•Itaimstoimplementreal-worldentitieslike
inheritance,polymorphisms,encapsulation,etc.
intheprogramming.
•PythonisnotjustanOOlanguagelikeJava/
Ruby,itisamixofmultipleprogramming
paradigms,likeitborrowsafewthingsfrom
functionallanguageslikeLispandHaskell.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 28

BCA
3.Scalable:
•Codereusability
•Addotherneworexistingpythonelements
•Encouragescleancodedesign
•Highlevelstructureandpackagingofmultiple
components–deliversflexibility,consistencyand
fasterdevelopmenttime.
•Scalablereferstomeasuringh/wthroughput
andadditionalperformancewhennewh/wis
addedtothesystem.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 29

BCA
4.Extensible:
•Aprogramminglanguageissaidtobeextensible
ifitcanbeextendedtootherlanguages.
•Pythoncodecanalsobewritteninother
languageslikeC(Cpython),C++,Java(Jython),C#
orVB.NET(IronPython)makingitahighly
extensiblelanguage.
•Ifpythoncodeincreases,codecanbeseparated
intomultiplefilesormodulesandbeableto
accesscodefromonemoduleandattributes
fromanother.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 30

BCA
5.Portable:
•Pythonisportableinthesensethatthesame
codecanbeusedondifferentmachines.
•SupposeyouwriteaPythoncodeonaMac.Ifyou
wanttorunitonWindowsorLinuxlater,you
don'thavetomakeanychangestoit.
•Assuch,thereisnoneedtowriteaprogram
multipletimesforseveralplatforms.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 31

BCA
6.EasytoLearn:
•Pythonisactuallyoneofthebestprogramming
languagesforbeginners.
•ItssyntaxissimilartoEnglish,whichmakesit
relativelyeasytoreadandunderstand.
•Withsometimeanddedication,youcanlearnto
writePython,evenifyou'veneverwrittenaline
ofcodebefore.
•Pythonhasfewkeywords,simplestructureand
clearlydefinedsyntax.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 32

BCA
7.EasytoRead:
•Becausethereadabilityandotherstructural
elementsofPythonaredesignedtobeeasyto
understand,especiallyforEnglishspeakers,it's
relativelyeasytolearn.
•Thisisagreatfirstorsecondlanguagefor
beginners.However,Pythonisnotlimitedto
basicuse.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 33

BCA
8.EasytoMaintain:
•Maintainingsourcecodeispartofthesoftware
developmentlifecycle.
•Easy-to-maintain−Python'ssourcecodeisfairly
easy-to-maintain.
•Abroadstandardlibrary−Python'sbulkofthe
libraryisveryportableandcross-platform
compatibleonUNIX,Windows,andMacintosh.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 34

BCA
9.Robust:
•Robustprogrammingisastyleofprogramming
thatfocusesonhandlingunexpectedtermination
andunexpectedactions.
•Itrequirescodetohandletheseterminations
andactionsgracefullybydisplayingaccurateand
unambiguouserrormessages.
•Theseerrormessagesallowtheusertomore
easilydebugtheprogram.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 35

BCA
10.EffectiveasaRapidPrototypingTool:
•PythonhasasimplesyntaxsimilartotheEnglish
language.
•Pythonhassyntaxthatallowsdevelopersto
writeprogramswithfewerlinesthansomeother
programminglanguages.
•Pythonrunsonaninterpretersystem,meaning
thatcodecanbeexecutedassoonasitiswritten.
•Thismeansthatprototypingcanbeveryquick.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 36

BCA
11.AMemoryManager:
•MemorymanagementinPythoninvolvesaprivate
heapcontainingallPythonobjectsanddata
structures.
•Themanagementofthisprivateheapisensured
internallybythePythonmemorymanager.
•Theprogrammerhastomanuallyallocatememory
beforeitcanbeusedbytheprogramandreleaseit
whentheprogramnolongerneedsit.
•InPython,memorymanagementisautomatic!
Pythonautomaticallyhandlestheallocationand
deallocationofmemory.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 37

BCA
12.InterpretedandByteCompiled:
•Pythonisclassifiedasaninterpretedlanguage,
meaningthatcompile-timeisnolongerafactor
duringdevelopment.
•Interpretedlanguagesareslowerthancompiled
languagesbecauseexecutiondoesnottakeplacein
asystem’snativebinarylanguage.
•LikeJava,Pythonisbyte-compiled,resultinginan
intermediateformclosertoMachineLanguage.
ThisimprovesPython’sperformance,allowsitto
retainalltheadvantagesofinterpretedlanguages.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 38

BCA
Pythonhasseveraladditionalfeatures
whichareasfollows:
•Ithasmanybuilt-indatatypes,strings,
lists,tuples,dictionaries,etc.
•Itsupportsmanycontrolstatements
suchasif,if-else,if–elseif-else,while,
iterativefor,etc.
•Itallowsforeasierprogrammingwith
theuseoffunctions,classes,modules
andpackages.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 39

BCA
PythonSyntaxcomparedtoother
programminglanguages:
Pythonwasdesignedforreadability,andhas
somesimilaritiestotheEnglishlanguagewith
influencefrommathematics.
Pythonusesnewlinestocompleteacommand,as
opposedtootherprogramminglanguageswhich
oftenusesemicolonsorparentheses.
Pythonreliesonindentation,usingwhitespace,to
definescope;suchasthescopeofloops,functions
andclasses.Otherprogramminglanguagesoften
usecurly-bracketsforthispurpose.
DEC-MAR 2025 40Dr. Reshmi. S I BCA B

BCA
Dr. Reshmi. S I BCA B 41DEC-MAR 2025
•ThemostrecentmajorversionofPython
isPython3.
•However,Python2,althoughnotbeing
updatedwithanythingotherthan
securityupdates,isstillquitepopular.
•ItispossibletowritePythoninan
IntegratedDevelopmentEnvironment,
suchasThonny,Pycharm,Netbeansor
Eclipsewhichareparticularlyuseful
whenmanaginglargercollectionsof
Pythonfiles.

BCA
Dr. Reshmi. S I BCA B 42DEC-MAR 2025

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B 43
PYTHON A SCRIPTING
LANGUAGE

BCA
–Pythonisahigh-level,interpretedscriptinglanguagethat
iswidelyusedforavarietyofprogrammingtasks.It
emphasizescodereadabilityandsimplicity,makingita
greatchoiceforbothbeginnersandexperienced
developers.
»Interpreted:Pythoncodeisexecutedlinebyline,which
makesiteasiertodebugandtest,comparedtocompiled
languages.
»DynamicallyTyped:Youdon'tneedtodeclarevariable
typesexplicitly.Theinterpreterinfersthetypeofavariable
atruntime,whichcontributestofasterdevelopmentbut
mayleadtoruntimeerrorsiftypesaremismatched.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 44

BCA
»ReadableSyntax:Python'ssyntaxisdesignedtobe
readableandclear,reducingthecomplexityofwritingand
understandingcode.Forexample,indentationisusedto
definecodeblocksinsteadofbraces{}.
»Cross-Platform:Pythonisavailableonmultipleplatforms
(Windows,Linux,MacOS)andallowsdeveloperstowrite
cross-platformscripts.
»ExtensiveLibraries:Pythonhasalargestandardlibrary,
whichmeansmanytasks(filehandling,database
connections,webscraping,etc.)canbedonewithminimal
externaldependencies.Additionally,Pythonhasarobust
ecosystemofthird-partylibraries.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 45

BCA
»Object-Oriented:Pythonsupportsobject-oriented
programming(OOP)concepts,whichmakesiteasierto
structureprogramsinamodularway.
»Versatile:Pythonisusedinawidevarietyoffields
includingwebdevelopment(e.g.,Django,Flask),data
analysis(e.g.,Pandas,NumPy),automation(e.g.,scripting
tasks),artificialintelligence(e.g.,TensorFlow,Keras),and
more.
»High-Level:Asahigh-levellanguage,Pythonabstractsaway
mostofthecomplexdetailsofcomputeroperations,
allowingdeveloperstofocusmoreonlogicthanonsystem-
specificdetails.
»CommunitySupport:Pythonhasanactiveandlarge
communityofdeveloperswhocontributetotutorials,
forums,andopen-sourceprojects.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 46

BCA
Dr. Reshmi. S I BCA B 47
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 48
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 49
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 50
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 51
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 52
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 53
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 54
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 55
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 56
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 57
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 58
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 59
DEC-MAR 2025

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B 60
USERS OF PYTHON

BCA
–Awiderangeoffinancialinstitutions,techcompanies,
governmentagencies,andmorelookforcandidateswho
haveamasteryofPythonforroleswithinwebandsoftware
developmentanddatascience,amongothers.
–Generallyspeaking,PythonDevelopers(sometimesjust
referredtoasWebDevelopers,or,morepreciselyBack-End
Developers)usePythontodevelopwebsites,applications,
games,andmore.
–DataScientistsusePythonforcomputinglargeamountsof
dataanddrawingfromlargedatabasesandlibraries.It’s
particularlyusefulforthosewhospecializeinmachine
learningasPythonisabletoaccessmachinelearning
frameworksforthoseworkingwithAI.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 61

BCA
–PythonisusedbyIntel,IBM,NASA,Pixar,Netflix,Facebook,
JPMorganChase,Spotify,andanumberofothermassive
companies.
–It’soneofthefourmainlanguagesatGoogle,whileGoogle’s
YouTubeislargelywritteninPython.
–SamewithReddit,Pinterest,andInstagram.
–TheoriginalBitTorrentclientwasalsowritteninPython.
–AnditisusedasascriptinglanguagetocontrolMaya,the
industrystandard3Dmodelingandanimationtool.
–Pythonisusedheavilyinacademicresearch,particularlyin
bioinformatics,biology,andmathematics.
–Itisthestandardintroductorylanguageformany
universitycomputerscienceprograms.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 62

BCA
–SomeofthemaingroupsandsectorsthatusePythontoday:
»SoftwareDevelopers:Forwebdevelopment(Django,
Flask)andautomationscripting.
»DataScientistsandAnalysts:Fordataanalysis,
manipulation,andvisualization(Pandas,NumPy).
»ResearchersandAcademics:Forscientificresearchand
simulationsinvariousfields.
»FinancialAnalysts:Forquantitativeanalysis,financial
modeling,andalgorithmictrading.
»DevOpsEngineers:Forautomatingdeployment
pipelinesandinfrastructuretasks.
»CybersecurityProfessionals:Forpenetrationtesting
andcreatingsecuritytools.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 63

BCA
»EmbeddedSystemsEngineers:Forscriptingon
microcontrollersandembeddeddevices(MicroPython).
»ScientistsandEngineers:Forsimulations,modeling,
anddataanalysis.
»BigTechCompanies:UsedbycompanieslikeGoogle,
Instagram,Spotify,Netflix,andDropbox.
»StartupsandEntrepreneurs:Forrapidprototypingand
productdevelopment.
»GovernmentandNonprofits:Fordataanalysisand
automatingadministrativetasks.
»Education:Widelyusedtoteachprogrammingin
schools,universities,andcodingbootcamps.
»AI&Robotics:ForAIapplications,computervision,and
roboticsdevelopment.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 64

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B 65
NEED OF PYTHON

BCA
–SimplicityandReadability:Python’ssyntaxisclean,easyto
read,andintuitive,makingitidealforbeginnersand
experienceddevelopersalike.Itreducesthecomplexityof
code,speedingupdevelopmenttime.
–Versatility:Pythoncanbeusedforawiderangeof
applications,includingwebdevelopment,dataanalysis,
machinelearning,automation,AI,scientificcomputing,and
more.Itsadaptabilitymakesitago-tolanguageforvarious
domains.
–LargeCommunityandEcosystem:Pythonhasavast
communityofdevelopers,whichmeansthereisawealthof
tutorials,resources,andthird-partylibraries(e.g.,NumPy,
TensorFlow,Django)availabletosupportdevelopment.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 66

BCA
–Cross-PlatformCompatibility:Pythonisavailableonall
majoroperatingsystems(Windows,Linux,macOS)andcan
runonmultipleplatformswithoutsignificantchangesto
thecodebase.
•Extensive Libraries and Frameworks: Python’s rich set of
libraries and frameworks simplifies complex tasks like web
scraping (BeautifulSoup), machine learning (Scikit-learn,
TensorFlow), and data manipulation (Pandas, NumPy).
•Rapid Prototyping: Python allows quick prototyping and
iterative development. Its ease of use means ideas can be
tested and refined quickly, which is essential for startups
and innovation-driven industries.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 67

BCA
–IntegrationCapabilities:Pythonintegrateswellwithother
languages(likeC,C++,andJava),systems,andtools.Italso
workswellwithdatabasesandwebservices,makingit
suitableforcomplexsystemdevelopment.
–PopularityinEmergingFields:Pythoniscrucialinrapidly
growingfieldssuchasartificialintelligence(AI),data
science,machinelearning,deeplearning,andautomation,
makingitanessentiallanguageformoderntechnological
advancements.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 68

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B 69
PYTHON’S TECHNICAL
STRENGTHS

BCA
–ItsRelativelyEasytouse.
–Itsfree
–Itsportable
–Itsgeneralpurposelanguage
–Itspowerful
–Dynamictyping
–Automaticmemorymanagement
–Programminginthelargesupport
–Built-inobjecttypes
–Built-inoperation
–Libraryutilitiesandthirdpartyutilities
–Itsmixable
–Itsobject-orientedandfunctional
DEC-MAR 2025 Dr. Reshmi. S I BCA B 70

BCA
Dr. Reshmi. S I BCA B 71
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 72
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 73
DEC-MAR 2025

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B 74
HOW PYTHON RUNS
PROGRAMS:
INTRODUCING THE
PYTHON
INTERPRETER

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B 75
How Python
Programs Works?

BCA
Dr. Reshmi. S I BCA B 76
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 77
DEC-MAR 2025

BCA
–APythonprogramstartsasatextfile
writteninacodeeditor,savedwith
a.pyextension.
–ThePythoninterpreterreadsthissource
code,analyzesit,andexecutesitlineby
line.
–Duringthisprocess,itperformslexical
analysis,parsing,andexecution.
–Optionally,thesourcecodecanbecompiled
intobytecodeforfasterexecution.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 78

BCA
–ThePythoninterpreteractsasavirtual
machine,executingthecodebyconverting
itintomachine-specificbinarycode.
–Theprogrammayutilizelibrarymodules
forvarioustasks.
–Whenrun,itcaninteractwiththesystem,
processdata,andproduceoutput.
–Anyerrorsorexceptionsarehandled
duringexecution.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 79

BCA
–Pythonisahigh-levelprogramminglanguage
knownforitssimplicityandreadability.
CodeEditor:
–YoustartbywritingyourPythoncodeina
codeeditor.
–Thisiswhereyoucreateyourprogramand
saveitwitha.pyextension.
–Acodeeditorprovidesfeaturesforwriting
andeditingcode,suchassyntaxhighlighting
andcodecompletion.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 80

BCA
–Openatexteditor,andwritethefollowing
code:
print("Hello,World!")
SourceFile:
–YourPythoncodeissavedinasourcefilewith
a.pyextension,e.g.,hello.py.Thisfilecontains
thetextofyourprogramwritteninPython's
syntax.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 81

BCA
Compiler(Optional):
–Pythonistypicallyaninterpretedlanguage,
meaning itdoesn'trequireexplicit
compilationbeforerunning.
–Insomecases,yourPythoncodemaybe
compiledintobytecode.
–Thiscompiledbytecodeissavedin.pycfiles.
–Thecompilationisnotsomethingyouusually
domanually;it'smanagedbythePython
interpreter.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 82

BCA
Bytecode:
–Bytecodeisanintermediaterepresentationof
yourPythoncode.
–It'salow-level,platform-independentformat
thatthePythoninterpretercanexecute.
–Bytecodefiles(.pyc)aregeneratedtoimprove
executionspeed.
–Ifthe.pycfileexistsandisnewerthanthe
sourcecode,Pythonusesitforfaster
execution.
–Inthecaseof"Hello,World!"wherethecode
issimple,Pythonoftenskipsthebytecode
step.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 83

BCA
PythonInterpreter(VirtualMachine):
–ThePythoninterpreterisresponsiblefor
executingyourPythoncode.Youexecutethe
Pythonprograminyourterminalor
commandprompt.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 84
python hello.py

BCA
ThePythoninterpreterreadshello.pyandperforms
severalstepsduringtheexecution:
–LexicalAnalysis:Itisthefirstphaseofacompiler
orinterpreterwherethesourcecodeisscanned
andbrokenintotokens.Itinvolvesidentifyingthe
basicbuildingblocksofaprogram,suchas
keywords,identifiers,operators,literals,and
punctuation.
–Parsing:Itconstructsaparsetreetounderstand
thecode'sstructureandlogic.
–Execution:Itexecutestheprogrambyfollowingthe
instructionsdefinedintheparsetree.Thisincludes
performingcalculations,I/Ooperations,and
functioncalls.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 85

BCA
LibraryModules:
–Pythonprovidesarichstandardlibrary,
whichincludesawiderangeofmodulesand
functionsforvarioustasks.
–Youcanimporttheselibrarymodulesinto
yourprogramtoextenditsfunctionality.
–Forexample,themathmoduleprovides
mathematicalfunctions,andtheosmodule
allowsyoutointeractwiththeoperatingsystem.
–Whilethe"Hello,World!"exampledoesn'tuseany
additionalmodules,youcanimportandusethem
inmorecomplexprogramstoextend
functionality.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 86

BCA
•Data Science & Machine Learning:
–NumPy:Fornumericaloperationsandmulti-
dimensionalarrays.Alibraryforscientificand
technicalcomputing,usedinlinearalgebra,statistical
analysis,andmachinelearning
–Pandas:For data manipulation and analysis.
–Matplotlib:For data visualization. A library for
creating static, animated and interactive
visualizations.
–SciPy:For scientific and technical computing.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 87

BCA
–TensorFlow:Formachinelearninganddeep
learning.Alibraryforhigh-levelcomputations,
machinelearning,deeplearningalgorithms,and
solvingcomplexmathematicalandphysicsproblems.
–PyTorch:Another popular machine learning and
deep learning library. This involves NLP or CV.
–Scikit-learn:For machine learning algorithms and
tools.
–PyGame: A package that provides an interface to the
Simple Directmedia Library (SDL) for graphic, audio,
and input libraries.
–Keras: A library for experimenting with deep neural
networks.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 88

BCA
•Web Development:
–Django:A high-level web framework for building
complex web applications.
–Flask:A micro web framework for building smaller,
simpler web applications.
•Web Scraping:
–BeautifulSoup:For extracting data from HTML and
XML files.
–Scrapy:A powerful framework for web scraping and
crawling.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 89

BCA
•Web Development:
–Django:A high-level web framework for building
complex web applications.
–Flask:A micro web framework for building smaller,
simpler web applications.
•Web Scraping:
–BeautifulSoup:For extracting data from HTML and
XML files.
–Scrapy:A powerful framework for web scraping and
crawling.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 90

BCA
•Other:
–Requests:For making HTTP requests.
–Pillow:For image processing.
–OpenCV:For computer vision.
–NLTK:For natural language processing.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 91

BCA
BinaryCode:
–ThePythoninterpreterconvertsthebytecode
intomachinecodethatisspecifictoyour
computer'sarchitecture.Thisisdone
dynamicallyduringtheexecutionofyour
Pythonprogram.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 92

BCA
RunningProgram:
–AsthePythoninterpreterexecutesthe
bytecode,yourPythonprogramruns,andit
caninteractwiththesystem,readandwrite
files,andproduceoutput.
–Ifthereareerrorsorexceptions,Pythonwill
handlethemaccordingtoyourcodeorraise
anerrorifnotcaught.
–Inthisexample,theprogramwillrunand
displaytheoutput:
Hello,World!
DEC-MAR 2025 Dr. Reshmi. S I BCA B 93

BCA
Completion
Theprogramexecutioncompletes,having
successfullyprintedHello,World!totheconsole.If
therewereerrorsorexceptionsinthecode,Python
wouldhandlethemaccordingly.
InthecaseofHello,World!,theprocessisrelatively
simple.Youwritethecodeinacodeeditor,saveitas
asourcefile,andexecuteitusingthePython
interpreter.Pythoninterpretsandexecutesthecode,
displayingtheoutput.ComplexPythonprograms
followasimilarprocess,withmoreintricatelogic
andpossiblytheuseoflibrarymodules.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 94

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B 95
Introducing the
Python Interpreter

BCA
Dr. Reshmi. S I BCA B 96
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 97
DEC-MAR 2025

BCA
•What are Interpreters?
–Interpretersarethecomputerprogramthat
willconvertthesourcecodeoranhighlevel
languageintointermediatecode(machine
levellanguage).
–Itisalsocalledtranslatorinprogramming
terminology.
–Interpretersexecuteseachlineofstatements
slowly.ThisprocessiscalledInterpretation.
–Forexample:Pythonisaninterpreted
language,PHP,Ruby,andJavaScript.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 98

BCA
Dr. Reshmi. S I BCA B 99
DEC-MAR 2025

BCA
•Example:
Here is the simple Python program that takes
two inputs asaandband prints the sum in the
third variable which isc. It follows sequential as
well as functional execution of programs
DEC-MAR 2025 Dr. Reshmi. S I BCA B 100

BCA
•How interpreters function in Python?
–PythoninterpreteriswritteninC
programminglanguageasweallknowthatC
isconsideredasmotherofallprogramming
languages,Pythoninterpretercalled
"CPython".
–Initiallyinsourcecodeanalysis,Pythonget
sourceandcheckforsomeIndentationrule
andcheckforerrors.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 101

BCA
–IfthereareanyerrorsPythonstopsitsexecution
andmaketomodifytopreventerrors.This
processiscalledLexicalanalysisinpythonwhich
statesthatdividingthesourcecodeintolistof
individualtokens.
–InBytecodegeneration,oncethepython
interpreterreceivesthetokens,itgeneratesAST
(AbstractStructuretree)whichconvertstobyte
codeandthenbytecodecanbesavedin(.py)
extension.
–Atlast,byusingPythonVirtualMachine,
interpreterloadsthemachinelanguageandPVM
convertsininto0sand1swhichprintsthe
results.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 102

BCA
–BYTECODE:
»BytecodeinPythonreferstoanintermediate,
low-levelrepresentationofPythoncodethatis
executedbythePythonVirtualMachine(PVM).
Itisaseriesofinstructionsthataregenerated
afterthePythonsourcecodeiscompiled.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 103

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B 104
Difference between
Compilers and
Interpreters

BCA
Dr. Reshmi. S I BCA B 105
DEC-MAR 2025
COMPILER INTERPRETER
Ittranslatesaprogramona
singlerun
Itexecutesaprogramlinebyline.
ItisanFastProcess ItisanSlowProcess
Itgeneratesoutputintheformof
.(exe)
Itdoesnotgenerateanyformof
outputs.
ItutilizesCPUmore. IttakeslessutilizationofCPU
ItisusedinProduction
environment
Itismaximum usedin
Programminganddevelopment
environment.
C,C++,C#arethecompiled
languages
Python,Ruby,PHParethe
interpretedlanguages.
Ittakeslotoftimetoanalyzethe
codestructure
Ittakeslesstimecomparedto
compilers.

BCA
•AdvantagesofusingInterpreter
–Itisflexibleanderrorlocalizationiseasier.
–Itissmallerinsize.
–Itexecuteslinebylineexecution.
•DisadvantagesofusingInterpreters
–Ittakeslotoftimetotranslate.
–Itisslower.
–Ituseslotofstorage.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 106

BCA
•ApplicationsofInterpreters
–Theyareusedtoexecutecommonlanguagesby
usingeditororancompiler.
–Easyimplementationofselfmodifyingcode.
–Virtualization.
–Sandboxing.
–Emulators.
•Interpretersofdifferentprogramminglanguage.
–Python-PyPy,StacklessPython,Pyston,
CPython,MicroPython,andRustPython.
–Java-JRocklt,Hotspot.
–Ruby-CRuby,MRI.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 107

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B 108
GETTING STARTED WITH PYTHON

BCA
BeginningwithPythonprogramming:
1)FindinganInterpreter
2)Writingfirstprogram
DEC-MAR
2025
Dr. Reshmi. S I BCA B 109

BCA
1)FindinganInterpreter:
–BeforewestartPythonprogramming,we
needtohaveaninterpretertointerpretand
runourprograms.
–Therearecertainonlineinterpreterslike
»https://ide.geeksforgeeks.org/
»http://ideone.com/
»http://codepad.org/thatcanbeusedto
startPythonwithoutinstallingan
interpreter.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 110

BCA
–Windows:Therearemanyinterpreters
availablefreelytorunPythonscriptslike
IDLE (Integrated Development
Environment)whichisinstalledwhenyou
installthepythonsoftwarefrom
http://python.org/
–Linux:ForLinux,Pythoncomesbundled
withtheLinux.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 111

BCA
1)WritingFirstProgram:
–FollowingisfirstprograminPython
# Script Begins
print(“Welcome")
# Scripts Ends
DEC-MAR 2025 Dr. Reshmi. S I BCA B 112
OUTPUT:
Welcome

BCA
–Line1:[#ScriptBegins]
»InPythoncommentsbeginwith#.Sothisstatementis
forreadabilityofcodeandignoredbyPython
interpreter.
–Line2:[print(“Welcome”)]
»InaPythonscripttoprintsomethingontheconsole
print()functionisused–itsimplyprintsoutaline(and
alsoincludesanewlineunlikeinC).
»OnedifferencebetweenPython2andPython3isthe
printstatement.InPython2,the“print”statementisnot
afunction,andthereforecanbeinvokedwithouta
parenthesis.However,inPython3,itisafunction,and
mustbeinvokedwithparentheses.
–Line3:[#ScriptEnds]
»ThisisjustanothercommentlikeLine1.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 113

BCA
Threedifferentwaysofstarting
Python:
–Runningascriptwritteninpython
–UsingaGUIfromanIntegrated
DevelopmentEnvironment(IDE)
–Employinganinteractiveapproach
DEC-MAR 2025 Dr. Reshmi. S I BCA B 114

BCA
•TheFirstapproachwillrequireaTEXT
EDITOR.Createourownscriptsandthen
executethemusingtheTextEditor.
•TheSecondapproachwillrequireaGUI
application,onethatcomeswiththePython
installeritself.
•TheThirdinteractiveapproachiscommand
lineinterpreterwhichisprovidedby
python.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 115

BCA
INSTALLING PYTHON INTERPRETER
a)InstallingonLinuxOS:
1.Downloadthe.tgzfileofPythonfromtheaboveprovided
downloadlink.
http://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz
2.Unzipthedownloadedfile.
tarxvfzPython-2.7.11.tgz
3.Gointothedirectory.
cdPython-2.7.11
DEC-MAR 2025 Dr. Reshmi. S I BCA B 116

BCA
4../configure
5.Buildit
6.Make
7.suorsudosuifthereisnorootuser
8.Makealtinstall
DEC-MAR 2025
Dr. Reshmi. S I BCA B 117

BCA
b)InstallingonWindowsOS:
•Firstofall,youneedtodownloadthePythonInstallerfrom
thelink:http://www.Python.org/downloads/
•Next,doubleclickontheinstalledfile.Astheinstaller
begins,youwillbeaskedtoselecttheusersforwhomyou
wanttheprogramstobeinstalled.
•ChooseInstallforallusersandclickNext>.
Note:Installingforallusersisrecommended.
DEC-MAR 2025
Dr. Reshmi. S I BCA B 118

BCA
•Nowchoosethedirectorywhereyouwanttoinstall
PythonandclickNext>.Itisbesttousethedefaultgives
location.
•Youwillbethenaskedtoselectthepackage.ClickNext>
•Pleasenotethatinstallationtakessometimeto
complete.
•Oncetheinstallationprocessiscomplete,clickonFinish
toexittheinstaller.
DEC-MAR 2025
Dr. Reshmi. S I BCA B 119

BCA
Pythonisnowinstalledinyourcomputer’s
directory.YouneedtorunPythonbyfollowing
thegivensteps:
1.ClickSTARTbutton.
2.GotoAllPrograms
3.SearchforPython2.7folder.
4.ClickPython(Commandline)
ThiswillstartthePythonCommandline.
DEC-MAR 2025
Dr. Reshmi. S I BCA B 120

BCA
OncePythonstarts,youwillseetheinterpreterstartup
message,indicatingversionandplatform.
Youwillalsobegiventhepythoninterpreterprompt,i.e.,
“>>>”whichisalsoknownaspythonchevronprompt.
The“>>>”indicatesthatpythoninterpreteriswaitingfor
anexpressionorcommand.
Theinteractiveenvironmentwhereweareinteractingwith
thepythoninterpreteriscalledtheconsoleorcommand
shell.
DEC-MAR 2025
Dr. Reshmi. S I BCA B 121

BCA
•Enterasimpleexpression8+9,ontheconsole.After
enteringtheexpression,presstheEnterkeytogettheresult.
>>>8+9
17 #Output
>>>
•TypethefollowingtextatthePythonpromptsandpress
Enter
>>>print(“Hello,Python!”)
Hello,Python!#Output
DEC-MAR 2025
Dr. Reshmi. S I BCA B 122

BCA
•Theprintstatementisusedtodisplayoutput
tothescreen.
•Manyshellscriptlanguagesusetheecho
commandforprogramoutput.
•Theprintstatement,pairedwiththestring
formatoperator(%),behavesevenmorelike
C’sprintf()function.
DEC-MAR 2025
Dr. Reshmi. S I BCA B 123

BCA
Dr. Reshmi. S I BCA B 124
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 125
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 126
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 127
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 128
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 129
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 130
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 131
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 132
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 133
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 134
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 135
DEC-MAR 2025

BCA
Dr. Reshmi. S I BCA B 136
DEC-MAR 2025
Wheneveryouaredoneinthepython
commandline,youcansimplytypethe
followingtoquitthepythoncommand
lineinterface:
exit()

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B
137
COMMENTS

BCA
•Justlikeotherprogramminglanguages,Python
allowsyoutoaddcommentsinthecode.
•Commentsareusedbytheprogrammertoexplain
thepieceofcodetoothersaswellastohimselfina
simplelanguage.
•Pythonusesthehashcharacter(#)forcomments.
•Putting#beforeatextensuresthatthetextwillnot
beparsedbytheinterpreter.
DEC-MAR 2025
Dr. Reshmi. S I BCA B 138

BCA
•Commentsdonotaffecttheprogrammingpartand
thePythoninterpreterdoesnotdisplayanyerror
messagesforcomments.
•Commentsshowupasitisintheprogramming.
•Itisagoodpracticetousecommentsforprogram
documentationinyourprogramsothatitbecomes
easierforotherprogrammerstomaintainor
enhancetheprogramwhenrequired.
DEC-MAR 2025
Dr. Reshmi. S I BCA B 139

BCA
ExamplesofComments:
CommentingwithouttheuseofHashmark(#):
>>>8+9addition
SyntaxError:invalidsyntax #Output
>>>
Intheaboveexample,‘addition’iswrittenwithout
theHashmark.
Asaresult,theinterpreteracceptstheword
‘addition’aspartofprogramming.
Since‘addition’isnotacommandinPython,an
errormessageisdisplayed.
DEC-MAR 2025
Dr. Reshmi. S I BCA B 140

BCA
CommentingusingHashmark(#):
>>>8+9#addition
17 #Output
>>>
Now,inthisexample,‘addition’iswrittenwitha
Hashmark.
Hence,theinterpreterunderstandsitasacomment
anddoesnotdisplayanyerrormessage.
DEC-MAR 2025
Dr. Reshmi. S I BCA B 141

BCA
1.WhatareComments?
–Commentsareannotationsmadebythe
programmer.
–Thesehelpotherprogrammers in
understandingthecode.
2.Whichcharacterisusedforcommenting
inPython?
–Hashmark(#)isusedforcommentingin
Python
DEC-MAR 2025
Dr. Reshmi. S I BCA B 142

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B
143
PROGRAM
EXECUTION

BCA
Dr. Reshmi. S I BCA B 144
DEC-MAR 2025

BCA
InPython,programexecutionreferstotheprocess
ofrunningaPythonscriptorprogram,which
involvesinterpretingthePythoncodeand
performingthetasksdescribedinthecode.
Pythonprogramexecutionworksstepbystep:
1.WritingaPythonScript
2.ExecutingtheProgram
3.BehindtheScenes:HowPythonExecutesaProgram
4.ErrorsDuringExecution
5.ToolstoDebugPythonExecution
DEC-MAR 2025
Dr. Reshmi. S I BCA B 145

BCA
DEC-MAR 2025
Dr. Reshmi. S I BCA B 146
1.WritingaPythonScript:
YouwriteaPythonprograminafilewiththe
extension.py.Forexample:
#hello.py
print("Hello,World!")

BCA
2.ExecutingtheProgram:
Youcanruntheprograminvariousways:
UsingtheCommandLine(Terminal):
–Opentheterminalorcommandprompt.
–NavigatetothedirectorycontainingyourPythonfile.
–Runthecommand:
pythonhello.py
–Output:
Hello,World!
DEC-MAR 2025
Dr. Reshmi. S I BCA B 147

BCA
UsinganIntegratedDevelopmentEnvironment(IDE):
–OpenthescriptinanIDElikePyCharm,VisualStudioCode,
Thonny,orIDLE.
–Clickthe"Run"buttontoexecutethescript.
–Output:
Hello,World!
UsingOnlineInterpreters:
–Youcanalsopasteyourcodeintoonlineplatformslike
Replit,JupyterNotebook,orGoogleColabandexecuteit
there.
DEC-MAR 2025
Dr. Reshmi. S I BCA B 148

BCA
3.BehindtheScenes:HowPythonExecutesaProgram:
LexicalAnalysis:
Theinterpreterbreaksthecodeintotokens(keywords,
operators,etc.).
Parsing:
ThetokensaregroupedintoastructurefollowingPython's
grammarrules(AbstractSyntaxTree-AST).
Compilation:
Thecodeisconvertedintoanintermediateformcalled
bytecode.
Example:Forprint("Hello,World!"),Pythongeneratesbytecode
instructions.
ExecutionbyPythonVirtualMachine(PVM):
ThebytecodeisexecutedbythePythonVirtualMachine(PVM),
translatingtheinstructionsintomachinecodeforthehardware.
DEC-MAR 2025
Dr. Reshmi. S I BCA B 149

BCA
Dr. Reshmi. S I BCA B 150
DEC-MAR 2025
Example: Python Execution Flow
Consider this program:
x = 10
y = 20
print("The sum is:", x + y)

BCA
Dr. Reshmi. S I BCA B 151
DEC-MAR 2025
Execution Steps
1.Lexical Analysis:
•The code is tokenized into parts like x, =, 10, y, 20,
print, etc.
2.Parsing:
•Python creates a syntax tree representing the structure
of the program.
3.Bytecode Generation:
•Python compiles the code into .pyc(bytecode).
4.Execution:
•The PVM executes the bytecode and prints:
The sum is: 30

BCA
4.ErrorsDuringExecution:
Pythonhandlesthreemaintypesoferrors:
1.SyntaxErrors:Errorsincodestructure.
print"Hello"#Missingparentheses
2.RuntimeErrors:Errorsduringprogram
execution.
print(1/0)#Divisionbyzero
3.LogicalErrors:Theprogramrunsbutgives
incorrectresults.
x,y=10,20print("Product:",x-y)#Logical
mistake
DEC-MAR 2025
Dr. Reshmi. S I BCA B 152

BCA
5.ToolstoDebugPythonExecution:
PrintStatements:Addprintstatementsto
debug.
Debugger:UsePythondebuggerslikepdb
orIDE-integratedtools.
StaticAnalysisTools:Toolslikepylintor
flake8forcodechecking.
DEC-MAR 2025
Dr. Reshmi. S I BCA B 153

BCA
DEC-MAR 2025
Dr. Reshmi. S I BCA B
154
STANDARD
TYPES

BCA
Numbers
•Integer
Boolean
LongInteger
•Floatingpointrealnumber
•Complexnumber
String
List
Tuple
Dictionary
DEC-MAR 2025 Dr. Reshmi. S I BCA B 155

BCA
DEC-MAR 2025
Dr. Reshmi. S I BCA B
156
OTHER BUILT-IN
TYPES

BCA
Type
NullObject(None)
File
Set/Frozenset
Function/Method
Module
Class
DEC-MAR 2025 Dr. Reshmi. S I BCA B 157

BCA
•TypeObjectsandthetypeTypeObject–
Theamountofinformationnecessaryto
describeatypecannotfitintoasinglestring.
Callingtype()withanobject:
>>>type(42)
<type‘int’>
DEC-MAR 2025 Dr. Reshmi. S I BCA B 158
•Typeofalltypeobjectsistype.
>>>type(type(42))
<type‘type’>

BCA
•None,Python’sNullObject–
PythonhasaspecialtypeknownastheNull
objectorNoneType.
Ithasonlyonevalue,None.
ThetypeNoneisNoneType.
ItdoesnothaveanyoperatorsorBIF(Builtin
function).
Nonehasnousefulattributesandalways
evaluatestohavingaBooleanFalsevalue.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 159

BCA
DEC-MAR 2025
Dr. Reshmi. S I BCA B
160
STANDARD
TYPE
OPERATORS

BCA
1.OBJECTVALUECOMPARISON
2.OBJECTIDENTITYCOMPARISON
3.BOOLEAN
DEC-MAR 2025 Dr. Reshmi. S I BCA B 161

BCA
1.OBJECTVALUECOMPARISON:
•Comparisonoperatorsareusedto
determineequalityoftwodatavalues
betweenmembersofthesametype.
•Thesecomparison operatorsare
supportedforallbuilt-intypes.
•ComparisonsyieldBooleanTrueorFalse
valuesbasedonthevalidityofthe
comparisonexpression.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 162

BCA
Dr. Reshmi. S I BCA B 163
DEC-MAR 2025

BCA
•AlistofPython’svaluecomparisonoperators:
DEC-MAR 2025 Dr. Reshmi. S I BCA B 164
OPERATOR FUNCTION
expr1< expr2expr1 is less than expr2
expr1> expr2expr1 is greater than expr2
expr1<= expr2expr1 is less than or equal to expr2
expr1>= expr2expr1 isgreaterthan or equal to expr2
expr1== expr2expr1 is equalto expr2
expr1!= expr2expr1 is not equal to expr2 (C-Style)
expr1<> expr2expr1 is not equal to expr2
(ABC/PascalStyle)

BCA
Numerictypeswillbecomparedaccordingtonumeric
valueinsignandmagnitude,stringswillcompare
lexicographically,etc..
Eg:
DEC-MAR 2025 Dr. Reshmi. S I BCA B 165
>>>2==2
True
>>>2.46<=8.33
True
>>>5+4j>=2-3j
True
>>>’abc’==‘xyz’
False
>>>’abc’>‘xyz’
False
>>>’abc’<‘xyz’
True
>>>[3,‘abc’]==[‘abc’,3]
False
>>>[3,‘abc’]==[3,‘abc’]
True

BCA
Multiplecomparisons–sameline:
Eg:
DEC-MAR 2025 Dr. Reshmi. S I BCA B 166
>>>3<4<7
True
>>>4>3==3
True
>>>4<3<5!=2<7
False

BCA
2.OBJECTIDENTITYCOMPARISON:
•Pythonsupportsthenotionofdirectly
comparingobjectsthemselves.
•Objectscanbeassignedtoothervariables
(byreference).
•Becauseeachvariablepointstothesame
(shared)dataobject,anychangeeffected
throughonevariablewillchangetheobject
andbereflectedthroughallreferencestothe
sameobject.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 167

BCA
•Eg:1
foo1andfoo2referencethesameobject
foo1=foo2=4.3
Bothfoo1andfoo2referencethesame
object.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 168
4.3
foo1
foo2

BCA
•Eg:2
foo1andfoo2referencethesameobject
foo1=4.3
foo2=foo1
Bothfoo1andfoo2referencethesame
object.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 169
4.3
foo1
foo2

BCA
•Eg:3
foo1andfoo2referencedifferentobjects
foo1=4.3
foo2=1.3+3.0
DEC-MAR 2025 Dr. Reshmi. S I BCA B 170
4.3
foo1
4.3
foo2

BCA
•Wecreateavariable,thenanotherthat
pointstothesameobject.
•Boththeisandnotidentifiersarepython
keywords.
>>>a=[5,‘hat’,-9.3]
>>>b=a
>>>aisb
True
>>>aisnotb
False
DEC-MAR 2025 Dr. Reshmi. S I BCA B 171
>>>aisb
False
>>>aisnotb
True

BCA
•StandardTypeObjectIdentityComparison
Operators:
DEC-MAR 2025 Dr. Reshmi. S I BCA B 172
OPERATOR FUNCTION
Obj1is obj2 Obj1is the same object as obj2
Obj1is not obj2Obj1is not the same object as obj2

BCA
3.BOOLEAN:
Expressionmaybelinkedtogetheror
negatedusingtheBooleanlogicaloperators
and,orandnotallofwhicharepython
keywords.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 173

BCA
•StandardTypeBooleanOperators:
DEC-MAR 2025 Dr. Reshmi. S I BCA B 174
OPERATOR FUNCTION
notexpr Logical NOT of expr(negation)
expr1 and expr2LogicalAND of expr1 and expr2
(conjunction)
expr1 and expr2LogicalOR of expr1 and expr2
(disjunction)

BCA
>>>x,y=3.1415926536,1024
>>>x<5.0
True
>>>not(x<5.0)
False
>>>(x<5.0)or(y>2.718281828)
True
>>>(x<5.0)and(y>2.718281828)
False
>>>not(xisy)
True
>>>3<4<7sameas(3<4)and(4<7)
True
DEC-MAR 2025 Dr. Reshmi. S I BCA B 175

BCA
DEC-MAR 2025
Dr. Reshmi. S I BCA B
176
STANDARD
TYPE BUILT-IN
FUNCTIONS

BCA
•StandardTypeBuilt-inFunctions:
DEC-MAR 2025 Dr. Reshmi. S I BCA B 177
FUNCTION OPERATION
cmp(obj1, obj2)Comparesobj1 and obj2 returns
integer iwhere i<0, i>0, i==0
repr(obj) Returns evaluatablestring
representation of obj
str(obj) Returns printablestring
representation of obj
type(obj) Determines type of objand return type
object

BCA
1.type()
•Syntaxfortype():
type(object)
•type()takesanobjectandreturnsitstype.
Thereturnvalueisatypeobject.
>>>type(4)
<type‘int’>
>>>type(‘HelloWorld!’)
<type‘string’>
>>>type(type(4))
<type‘type’>
DEC-MAR 2025 Dr. Reshmi. S I BCA B 178

BCA
2.cmp()
•Thecmp()BIFCoMParestwoobjects,obj1
andobj2andreturns
•anegativenumber(integer)ifobj1isless
thanobj2,
•apositivenumberifobj1isgreaterthan
obj2,
•Zeroifobj1isequaltoobj2
DEC-MAR 2025 Dr. Reshmi. S I BCA B 179

BCA
•Thecomparisonusedistheonethatapplies
forthattypeofobject,whetheritbea
standardtypeorauser-createdclass.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 180
>>>a,b=-4,12
>>>cmp(a,b)
-1
>>>cmp(b,a)
1
>>>b=-4
>>>cmp(a,b)
0
>>>a,b=‘abc’,‘xyz’
>>>cmp(a,b)
-23
>>>cmp(b,a)
23
>>>b=‘abc’
>>>cmp(a,b)
0

BCA
3.str()andrepr()(and‘‘operator):
str()STRingandrepr()REPResentation
BIFsorthesinglebackorreversequote
operator(‘‘).
>>>str(4.53-2j)
‘(4.53-2j)’
>>>str(1)
‘1’
DEC-MAR 2025 Dr. Reshmi. S I BCA B 181
>>>str(2e10)
‘20000000000.0’
>>>repr([0,5,9,9])
‘[0,5,9,9]’

BCA
4.type()andisinstance():
•Pythondoesnotsupportmethodor
functionoverloading.
•Type()returnsthetypeforanyPython
object,notjustthestandardtypes.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 182

BCA
>>>type(‘‘)
<type‘str’>
>>>s=‘xyz’
>>>type(s)
<type‘str’>
>>>type(100)
<type‘int’>
>>>type(())
<type‘tuple’>
DEC-MAR 2025 Dr. Reshmi. S I BCA B 183
>>>type(0+0j)
<type‘complex’>
>>>type(0L)
<type‘long’>
>>>type(0.0)
<type‘float’>
>>>type([])
<type‘list’>
>>>type({})
<type‘dict’>

BCA
Python Type Operator and BIF Summary
DEC-MAR 2025 Dr. Reshmi. S I BCA B 184

BCA
Dr. Reshmi. S I BCA B 185
DEC-MAR 2025

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B
186
EXECUTION MODEL
VARIATION:
PYTHON
IMPLEMENTATION
ALTERNATIVES

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B
187
Execution model
variation

BCA
InteractiveModeExecution
Codeisexecutedline-by-lineinthePython
interpreter.
Suitablefortestingandquickexperiments.
Example:
>>>print("Hello,World!")
Hello,World!
ScriptModeExecution
Codeisstoredina.pyfileandexecutedasawhole.
Suitableforfull-fledgedprograms.
Execution:
pythonscript.py
DEC-MAR 2025 Dr. Reshmi. S I BCA B 188

BCA
ModuleImportExecution
Codeisstoredinamodule(.pyfile)andexecuted
indirectlythroughimport.
Onlytop-levelstatementsareexecutedduringimport.
Example:
#inmymodule.py
print("Thisrunsduringimport!")
#Inanotherscript
importmymodule
#Prints:Thisrunsduringimport!
DEC-MAR 2025 Dr. Reshmi. S I BCA B 189

BCA
EmbeddedExecution
Pythoncodeisembeddedwithinanothersystem,such
asawebserver,orexecutedviaaframework.
Example:
1.Pythonscriptsembeddedinautomationtools.
2.WebframeworkslikeFlaskorDjangohandling
Pythoncodeexecution.
Command-LineExecution
SpecificcodepasseddirectlytoPythonviathe
commandlineusingthe-coption.
Example:
python-c"print('Hello,World!')"
DEC-MAR 2025 Dr. Reshmi. S I BCA B 190

BCA
ExecutioninFrozenBinaryExecutables
Pythonscriptsareconvertedintoexecutablesusing
toolslikePyInstallerorcx_Freeze.
ThePythoninterpreterisbundledwiththecode.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 191
REPL(Read-Eval-PrintLoop)Execution
Extensionsoftheinteractivemode,oftenwithadded
features(e.g.,IPythonorJupyterNotebook).
Codeisexecutedinchunks(cells).

BCA
AsynchronousandConcurrentExecution
Usingconstructslikeasyncandawaitfor
asynchronoustasks.
Allowsfornon-blockingcodeexecution.
Example:
importasyncio
asyncdefgreet():
print("Hello,AsyncWorld!")
asyncio.run(greet())
DEC-MAR 2025 Dr. Reshmi. S I BCA B 192

BCA
Explanation
importasyncio:
Theasynciomoduleisimported,whichprovidessupportfor
asynchronousprogramminginPython.
asyncdefgreet():
Thisdefinesanasynchronousfunctiongreetusingtheasync
defsyntax.Insidethefunction,itsimplyprints"Hello,Async
World!".
asyncio.run(greet()):
Thisfunctionisusedtorunanasyncco-routine.
Itsetsuptheeventloop,runstheco-routineuntilitcompletes,
andthenclosestheeventloop.
Here,itexecutesthegreetco-routine,whichprintsthe
messagetotheconsole.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 193

BCA
DEC-MAR 2025 Dr. Reshmi. S I BCA B
194
Python
implementation
alternatives

BCA
Therearefiveprimaryimplementationsofthe
Pythonlanguage:
CPython
Jython
IronPython
Stackless
PyPy
Otherincludesasoptimizationtoolsbecausetheydo
notimplementthestandardPythonlanguage.
Cython
ShedSkinsystems
DEC-MAR 2025 Dr. Reshmi. S I BCA B 195

BCA
Cpython–TheStandard
Definition:
Thedefaultandmostwidelyusedimplementation
ofPython,writteninC.
ItfollowstheofficialPythonspecificationsandis
maintainedbythePythonSoftwareFoundation.
Features:
DirectlyexecutesPythoncodebyinterpretingit
intobytecodeandrunningitontheCPython
VirtualMachine.
SupportsCextensionsforperformance
improvements.
CompatiblewithmostPythonlibraries.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 196

BCA
Jython–PythonforJava
Definition:
APythonimplementationwritteninJavathat
runsontheJavaVirtualMachine(JVM).Itallows
seamlessintegrationbetweenPythonandJava.
Features:
PythoncodecancallJavalibrariesdirectlyand
viceversa.
UsefulforJavadeveloperswhoneedPython
scriptingcapabilities.
LimitedcompatibilitywithCPythonlibraries(e.g.,
Cextensionsarenotsupported).
DEC-MAR 2025 Dr. Reshmi. S I BCA B 197

BCA
IronPython–Pythonfor.NET
Definition:
APythonimplementationwritteninC#thatruns
onthe.NETframeworkandintegrateswith.NET
applications.
Features:
Pythoncodecaninteractwith.NETlibrariesand
applications.
PrimarilyusedinMicrosoftenvironments.
DoesnotsupportsomeCPython-specificlibraries,
suchasthoserelyingonCextensions.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 198

BCA
StacklessPython–Pythonforconcurrency
(managemultipletasksatonce,improvingperformanceandresponsiveness)
Definition:
APythonimplementationthatemphasizes
concurrencybyavoidingtherelianceontheCcall
stack.Itallowstheexecutionoflightweight
microthreads(tasklets).
Features:
Enablesefficientconcurrencywithoutusing
traditionalOSthreads.
Idealforapplicationsrequiringhighperformance
andscalability,likegamesandsimulations.
FullycompatiblewithCPython'slanguage
features.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 199

BCA
PyPy–Pythonforspeed
Definition:
APythonimplementationwithaJust-In-Time
(JIT)compilerdesignedforperformance
optimization.ItiswritteninPython(RPython
subset).
Features:
SignificantlyfasterexecutionformanyPython
programscomparedtoCPython.
CompatiblewithmostPythonlibraries.
Focusedonreducingruntimeoverheadthrough
JITcompilation.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 200

BCA
Cython
Definition:
CythonisasupersetofPythondesignedto
facilitatethedevelopmentofCextensionsfor
Python.ItallowsyoutowritePythoncodewith
optionalstatictyping,whichisthencompiledinto
highlyefficientCcode.
Features:
PerformanceBoost:SpeedsupPythoncodeby
convertingitintoCandenablingdirect
interactionwithC-levellibraries.
StaticTyping:Youcandeclarevariabletypes,
leadingtofurtherperformanceoptimization.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 201

BCA
Features:
Compatibility:Itworksseamlesslywithexisting
Pythoncodebases.
UseCase:Oftenusedincomputationallyintensive
taskssuchasnumericalcomputations,machine
learning,anddatascience.
Example:
#Cythoncodewithstatictyping
defadd(inta,intb):
returna+b
DEC-MAR 2025 Dr. Reshmi. S I BCA B 202

BCA
ShedSkinSystems
Definition:
ShedSkinisanexperimentalPython-to-C++
compilerthattranslatesasubsetofPythoncode
intoC++code.Itfocusesonstatictyping,
convertingPythonprogramsintooptimizedC++
implementations.
Features:
PerformanceOptimization:GeneratesC++code
forfasterexecutionofPythonprograms.
StaticTyping:RequiresPythonprogramsto
adheretotypeconstraints,asitdoesnotsupport
Python’sdynamicfeatures(e.g.,eval,dynamic
typing).
DEC-MAR 2025 Dr. Reshmi. S I BCA B 203

BCA
Features:
SubsetofPython:Onlysupportsastaticallytyped
subsetofPython,whichlimitsitscompatibility
withfullydynamicPythonprograms.
UseCase:Usefulforperformance-critical
applicationsthatcanfitwithinitsstatictyping
constraints.
Example:
#PythoncodecompatiblewithShedSkin
deffib(n):
ifn<=1:
returnn
returnfib(n-1)+fib(n-2)
DEC-MAR 2025 Dr. Reshmi. S I BCA B 204

BCA
BothtoolsaimtoenhancePython's
performance but with differing
approaches:
CythonfocusesonPythonwithC-like
enhancementsandintegration.
ShedSkincompilesPythonintoC++for
speedbutsacrificesPython’sdynamic
nature.
DEC-MAR 2025 Dr. Reshmi. S I BCA B 205

BCA
DEC-MAR 2025
Dr. Reshmi. S I BCA B 206
DEPARTMENTOFCOMPUTERSCIENCE&APPLICATIONS