Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide...
Transcript of Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide...
![Page 1: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/1.jpg)
![Page 2: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/2.jpg)
CompleteGuideForPythonProgramming
Quick&EasyGuideToLearnPython
By:JamesP.Long
ACKNOWLEDGMENTS
Formy students and friends,who all selflessly helpedme inwriting this book.Specialthanks to those who asked, insisted and assisted me in turning the seminars in [email protected]
TableofContentsIntroduction………………………………………10
PythonVersions…………………………………13
SomeCommonlyusedOperationsinPython………………………………………………15
PrintfFormatStrings…………………………20
Python Interactive - Using Python As A Calculator
![Page 3: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/3.jpg)
………………………………………….22
PythonImplementations……………………26
PythonCompilers&NumericalAccelerators………………………………………31
LogicalAndPhysicalLineinPython……34
PythonIndentation……………………………37
PythonStandardLibrary……………………39
CreatingClasses&Objects…………………43
DocumentingYourCode……………………46
Python-ObjectOrientedProgramming49
PythonDatabase………………………………..55
Classes………………………………………………65
Methods……………………………………………71
Instances…………………………………………..75
PythonDatabaseAccess…………………….82
PythonNetworking………………………….108
SendingMailinPython…………………….117
Pythonmultithreading…………………….127
Pythonxmlprocessing…………………….148
PythonPrograms…………………………….166
PythonProgramtoAddTwoMatrices166
Python Program to Add Two Numbers………………………………………………………..168
Python Program to Calculate the Area of a Triangle…………………………………………..169
Python Program to Check Armstrong Number…………………………………………..171
Python Program to Check if a Number is Odd or Even…………………………………….173
PythonProgramtoCheckifaNumberisPositive,NegativeorZero…………………174
PythonProgramtoCheckifaStringisPalindromeorNot……………………………177
PythonProgramtoCheckLeapYear…179
Python Program to Check Prime Number………………………………………………………..181
Python Program toConvert Celsius To Fahrenheit………………………………………
![Page 4: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/4.jpg)
183
PythonProgramtoConvertDecimalintoBinary,OctalandHexadecimal…………184
PythonProgramtoConvertDecimaltoBinaryUsingRecursion……………………186
Python Program to Convert Kilometers to Miles……………………………………………….187
Python Program to Count the Number of Each Vowel………………………………………189
PythonProgramtoDisplayCalendar..190
PythonProgramtoDisplayFibonacciSequenceUsingRecursion……………….192
PythonProgramToDisplayPowersof2UsingAnonymousFunction……………..194
PythonProgramtoDisplaythemultiplicationTable…………………………196
PythonProgramtoFindArmstrongNumberinanInterval………………………198
Python Program to Find ASCII Value of Character………………………………………..200
PythonProgramtoFindFactorialofNumberUsingRecursion…………………201
PythonProgramtoFindFactorsofNumber…………………………………………..203
PythonProgramtoFindHashofFile…205
PythonProgramtoFindHCForGCD…207
PythonProgramtoFindLCM……………209
PythonProgramtoFindNumbersDivisiblebyAnotherNumber……………211
PythonProgramtoFindSumofNaturalNumbersUsingRecursion………………..212
Python Program to Find the Factorial of a Number…………………………………………..214
PythonProgramtoFindtheLargestAmongThreeNumbers…………………….216
PythonProgramtoFindtheSize(Resolution)ofImage………………………218
Python Program to Find the Square Root………………………………………………………..220
PythonProgramtoFindtheSumofNaturalNumbers……………………………..221
Python Program to Generate a Random Number…………………………………………..222
Python Program to Illustrate Different Set Operations………………………………………223
PythonProgramtoMakeaSimpleCalculator………………………………………225
Python Program to Multiply Two Matrices………………………………………………………..229
![Page 5: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/5.jpg)
PythonProgramtoPrintallPrimeNumbersinanInterval…………………….231
PythonProgramtoPrintHi,GoodMorning!…………………………………………234
Pythonprogram toPrint theFibonacci sequence…………………………………………235
Python Program to Remove Punctuations form a String……………………………………237
Python Program to Shuffle Deck of Cards………………………………………………………..239
PythonProgramtoSolveQuadraticEquation………………………………………….241
PythonProgramtoSortWordsinAlphabeticOrder……………………………..243
Python Program to Swap Two Variables………………………………………………………..245
Python Program to Transpose a Matrix………………………………………………………..246
Note………………………………………………..248
MoreFromAuthor…………………………..249
INTRODUCTION
Python is a wide used general, high-level programming language. Its style philosophyemphasizescodereadability,anditssyntaxallowsprogrammerstopreciseideasinfewerlinesofcodethatmightbepossibleinlanguageslikeC++orJava.Thelanguageprovidesconstructssupposedtomodifyclearprogramsonbothsmallandlargescales.
![Page 6: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/6.jpg)
Python is a simple to learn, powerful programming language. Its economical high-levelinformation structures and an easy, but effective approach to object-orientedprogramming. Python’s elegant syntax and dynamic typing, in conjunction with itsinterpreted nature, make it a perfect language for scripting and speedy applicationdevelopmentinseveralareasonmostplatforms.Pythonisoneinallthoserarelanguageswhich might claim to both easy and powerful. You may end up pleasantly stunned toexaminehoweasy it’s to thinkabout theanswer to thematter insteadof thesyntaxandstructureofthelanguageyouareprogrammingin.
Inmyfirstbook“PythonProgrammingforBeginners”,Ihavediscussedallaboutwhatpythonprogramming language is?How to installpython toyour system?Differentdatatypes, function, parameters, class, objects used in python. I also have discussed aboutbasicpythonoperatorsandmodules.Notonlythese,youcanalsogetknowledgeonhowto call a function, exception handling function, python variables etc. That is all basicthingsthataremustknowwhenyoustartlearninganyprogramminglanguage.
NowinthisbookIamgoingtosharewithyouadvancedpythonprogrammingfunctionsandprogramstocreateinpython?Iassureyouthatifyougothroughthisbookseriously,theninfewdaysyouwillbecomeanexpertpythonprogrammer.Sowhatareyouwaitingfor?Startgoingthroughthebookandstartcreatingyourfirstprogramtoday.
PYTHONVERSIONS
Python has many versions but most commonly used are Python 2.0 and Python 3.0.Python2.0wasreleasedon16October2000,withmanymajornewfeaturesincludingafullgarbagecollectorandsupportforUnicode.Withthisreleasethedevelopmentprocesswas changed and becamemore transparent and community-backed. while Python 3.0 ,whichisalsoknownasPython3000orpy3k,isamajor,backwards-incompatiblerelease,andwasreleasedon3December2008.Manyofitsmajorfeatureshavebeenbackportedtothebackwards-compatiblePython2.6and2.7.Python2.xis legacy,Python3.xis thepresentandfutureofthelanguage.
![Page 7: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/7.jpg)
Python3.0wasreleasedin2008.Thefinal2.xversion2.7releasecameoutinmid-2010,withastatementofextendedsupportforthisend-of-liferelease.The2.xbranchwillseeno newmajor releases after that. 3.x is under active development and has already seenover five years of stable releases, including version 3.3 in 2012 and 3.4 in 2014. Thismeans that all recent standard library improvements, for example, areonlyavailablebydefaultinPython3.x.
For those interested in using Python via aUSB thumb drive, youmay be interested inPortablePython.Thisisaself-containedPythonenvironmentthatyoucaneitherrunfromthethumbdriveorinstalltoyourcomputer.Thisisusefulforpeoplewhocan’tordon’twanttoinstallPythonbutwouldstillliketouseit.
SOMECOMMONLYUSEDOPERATIONSINPYTHON
UsingBlankLines:
A line containingonlywhitespace, possiblywith a comment, is called a blank line andPython ignores it completely. In an interactive interpreter session, you must enter anemptyphysicallinetoterminateamultilinestatement.
WaitingfortheUser:
The following line of the programdisplays the prompt, Press the enter key to exit andwaitsfortheusertopresstheEnterkey:
#!/usr/bin/pythonraw_input(“\n\nPresstheenterkeytoexit.”)
Here,“\n\n”arebeingusedtocreatetwonewlinesbeforedisplayingtheactualline.Oncetheuserpressesthekey,theprogramends.Thisisanicetricktokeepaconsolewindowopenuntiltheuserisdonewithanapplication.
MultipleStatementsonaSingleLine:
The semicolon (;) allows multiple statements on the single line given that neitherstatementstartsanewcodeblock.Hereisasamplesnipusingthesemicolon:
importsys;a=‘abc’;sys.stdout.write(a+‘\n’)
MultipleStatementGroupsasSuites:
In Python, a group of statements, which make a single code block are called suites.Compound or complex statements, such as if, while, def, and class, are those whichrequireaheaderlineandasuite.Headerlinesbeginthestatementandterminateswithacolon(:)andarefollowedbyoneormorelines,whichmakeupthesuite.Forexample:
![Page 8: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/8.jpg)
ifexpression:suite
elifexpression:suite
else:suite
AccessingCommand-LineArguments:
Python provides a getopt module that helps you parse command-line options andarguments.
$pythontest.pyarg1arg2arg3
ThePythonsysmoduleprovidesaccesstoanycommand-lineargumentsviathesys.argv.Thisservestwopurpose:
•sys.argvisthelistofcommand-linearguments.
•len(sys.argv)isthenumberofcommand-linearguments.
ParsingCommand-‐LineArguments:Python provides a getopt module that helps you parse command-line options andarguments.Thismoduleprovidestwofunctionsandanexceptiontoenablecommand-lineargumentparsing.
getopt.getoptmethod:
Thismethodparsescommand-lineoptionsandparameterlist.Followingissimplesyntaxforthismethod:
getopt.getopt(args,options[,long_options])
Hereisthedetailoftheparameters:
•args:Thisistheargumentlisttobeparsed.
•options:Thisisthestringofoptionlettersthatthescriptwantstorecognize,withoptionsthatrequireanargumentshouldbefollowedbyacolon(:).
•long_options:Thisisoptionalparameterandifspecified,mustbealistofstringswiththenamesofthelongoptions,whichshouldbesupported.Longoptions,whichrequireanargumentshouldbefollowedbyanequalsign(‘=’).Toacceptonlylongoptions,optionsshouldbeanemptystring.
![Page 9: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/9.jpg)
PRINTFFORMATSTRINGS
%d:integer
%5d:integerinafieldofwidth5chars
%-5d:integerinafieldofwidth5chars,butadjustedtotheleft
%05d:integerinafieldofwidth5chars,paddedwithzeroesfromtheleft
%g:floatvariablein%for%gnotation
%e:floatvariableinscientificnotation
%11.3e:floatvariableinscientificnotation,with3decimals,fieldofwidth11chars
%5.1f:floatvariableinfixeddecimalnotation,withonedecimal,fieldofwidth5chars
%.3f:floatvariableinfixeddecimalform,withthreedecimals,fieldofmin.width
%s:string
%-20s:stringinafieldofwidth20chars,andadjustedtotheleft
PYTHONINTERACTIVE-USINGPYTHONASACALCULATOR
Youcanusepythonasacalculator,asyoucanadd,subtract,multiplyanddividenumbersinpythonlanguage.
StartPython(orIDLE,thePythonIDE).
Apromptisshowingup:
![Page 10: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/10.jpg)
>>>
Displayversion:
>>>help()
WelcometoPython2.7!Thisistheonlinehelputility.
…
help>
Helpcommands:
modules:availablemodules
keywords:listofreservedPythonkeywords
quit:leavehelp
Togethelponakeyword,justenteritsnameinhelp.
CommonOperatorsinPython
ExampleForSimpleCalculationsinPython
>>>3.14*5
15.700000000000001
TakecareinPython2.xifyoudividetwonumbers:
Isn’tthisstrange:
>>>35/6
5
Obviouslytheresultiswrong!
But:
>>>35.0/6
![Page 11: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/11.jpg)
5.833333333333333
>>>35/6.0
5.833333333333333
In the first example, 35 and 6 are interpreted as integer numbers, so integer division isusedandtheresultisaninteger.
This uncanny behavior has been abolished in Python 3, where 35/6 gives5.833333333333333.
In Python 2.x, use floating point numbers (like 3.14, 3.0 etc….) to force floating pointdivision!
PYTHONIMPLEMENTATIONS
An“implementation”ofPythonprovidessupportfortheexecutionofprogramswhicharewritten in the Python Programming language, is represented by the CPython referenceimplementation.Thereseveralimplementationtorunpythonprograms.Let’shavealookatthem:
CPythonVariants
These are implementations which are based on the CPython runtime core, but withextendedbehaviororfeaturesinsomeaspects.
CrossTwineLinker-AcombinationofCPythonandanadd-onlibraryofferingimprovedperformance.
Stackless Python - CPython with an emphasis on concurrency using tasklets andchannels.
Unladen-Swallow-anoptimizationbranchofCPython,intendedtobefullycompatibleandsignificantlyfaster.
WPython-are-implementationofCPythonusing“wordcode”insteadofbytecode.
![Page 12: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/12.jpg)
OtherImplementationsThesearere-implementationsofthePythonlanguagethatdonotdependontheCPythonruntime core. Many of them reuse the standard library implementation. The onlyimplementationsthatareknowntobecompatiblewithagivenversionofthelanguageareIronPython,JythonandPyPy.
The following implementations are comprehensive or even complete, that you can runtypicalprogramswiththemalready:
Brython-AwaytorunPythoninthebrowserthroughtranslationtoJavaScript.
CLPython-PythoninCommonLisp.
HotPy -Avirtualmachine forPython supportingbytecodeoptimizationand translationusingtypeinformationgatheredatrun-time.
IronPython - Python in C# for the Common Language Runtime (CLR/.NET) and theFePyproject’sIronPythonCommunityEdition(IPCE).
Jython-PythoninJavafortheJavaplatform.
Pyjs-APythontoJavaScriptcompilerplusWeb/GUIframework.
PyMite-Pythonforembeddeddevices.
PyPy-PythoninPython,targetingseveralenvironments.
Pyvm - A Python-related virtual machine and software suite providing a nearly self-contained“userspace”system.
RapydScript-APython-likelanguagethatcompilestoJavaScript.
SNAPpy-AsubsetofthePythonlanguagethathasbeenoptimizedforuseinlow-powerembeddeddevices.
Tinypy-AminimalistimplementationofPythonin64Kofcode.
TentativeImplementationsThefollowing implementationsareapparentworks inprogress; theymaynotbeable toruntypicalprograms:
Berp-animplementationofPython3inHaskell,providinganinteractiveenvironmentaswellasacompiler.
Phpython-aPythoninterpreterwritteninPHP.
![Page 13: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/13.jpg)
Pyjaco-aPythontoJavaScriptcompilersimilartoPyjsbutlighterweight.
Pystacho-is,likeSkulpt,PythoninJavaScript.
Pyvm2.py-aCPythonbytecodeinterpreterwritteninPython.
Skulpt-PythoninJavaScript.
Typhon-aRubinius-basedimplementationofPython.
PythonCompilers&NumericalAccelerators
Compilers
ThesecompilersusuallyimplementsomethingclosetoPython,havealookatthem:
2c-python-astaticPython-to-Ccompiler,apparentlytranslatingCPythonbytecodetoC.
Compyler-anattemptto“transliteratethebytecodeintox86assemblies”.
Cython - a widely used optimizing Python-to-C compiler, CPython extension modulegenerator, and wrapper language for binding external libraries. Interacts with CPythonruntimeandsupportsembeddingCPythoninstand-alonebinaries.
GCCPythonFront-End-anin-progressefforttocompilePythoncodewithintheGCCinfrastructure.
Nuitka - a Python-to-C++ compiler using libpython at run-time, attempting somecompile-timeandrun-timeoptimizations.InteractswithCPythonruntime.
Pyc - performs static analysis in order to compile Python programs, uses similartechniquestoShedSkin.
ShedSkin-aPython-to-C++compiler,restrictedtoanimplicitlystaticallytypedsubsetofthelanguageforwhichitcanautomaticallyinferefficienttypesthroughwholeprogramanalysis.
UnPython-aPythontoCcompilerusingtypeannotations.
NumericalAccelerators
Copperhead - purely functional data-parallel Python compiles to multi-core and GPUbackends.
![Page 14: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/14.jpg)
Numba-NumPy-awareoptimizingruntimecompilerforPython.
Parakeet-runtimecompilerforanumericalsubsetofPython.
LogicalAndPhysicalLineinPython
Aphysical lineiswhatyouseewhenyouwritetheprograminpython.Alogical lineiswhatPythonseesasasinglestatement.Pythonimplicitlyassumesthateachphysicallinecorrespondstoalogicalline.Forexample,youwanttowrite-‘helloworld’-ifthiswasonalinebyitself,thenthisalsocorrespondstoaphysicalline.
Ifyouwanttospecifymorethanonelogicallineonasinglephysicalline,thenyouhaveto explicitly specify this using a semicolon (;) which indicates the end of a logicalline/statement.
Forexample:
i=12
printi
iseffectivelysameas
i=12;
printi;
whichisalsosameas
i=12;printi;
andsameas
i=12;printi
Ifyouhavealonglineofcode,youcanbreakitintomultiplephysicallinesbyusingthebackslash.Thisisreferredtoasexplicitlinejoining:
s=‘Thisisapythonbook.\
Thiscontinuesthebook.’
prints
![Page 15: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/15.jpg)
Output:
Thisisapythonbook.Thiscontinuesthebook.
Similarly,
print\
i
isthesameas
printi
Sometimes,thereisanimplicitassumptionwhereyoudon’tneedtouseabackslash.Thisis the casewhere the logical line has starting parentheses, starting square brackets or astartingcurlybracesbutnotanendingone.Thisiscalledimplicitlinejoining.Youcanseethisinactionwhenwewriteprogramsusinglistsinlaterchapters.
PYTHONINDENTATION
Whitespace is very important inPython.Thewhitespace at the beginning of the line iscalled indentation. Leading whitespace at the beginning of the logical line is used todeterminetheindentationlevelofthelogicalline,whichinturnisusedtodeterminethegroupingofstatements.Eachsetofstatementsiscalledablock.
Forexample:
i=5
#Errorbelow!Noticeasinglespaceatthestartoftheline
print‘Valueis‘,i
print‘Irepeat,thevalueis‘,i
Whenyourunthis,yougeterror:
File“whitespace.py”,line5
print‘Valueis‘,i
^
IndentationError:unexpectedindent
Noticethatthereisasinglespaceatthebeginningofthesecondline.Theerrorindicatedby Python tells us that the syntax of the program is invalid i.e. the program was notproperly written. Use four spaces for indentation. This is the official Python language
![Page 16: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/16.jpg)
recommendation.Good editorswill automaticallydo this for you.Make sureyouuse aconsistent number of spaces for indentation; otherwise your programwill show errors.Pythonalwaysuseindentationforblocksandwillneverusebraces.
PYTHONSTANDARDLIBRARY
ThePython StandardLibrary contains a huge number of usefulmodules and is part ofeverystandardPythoninstallation.wewillexploresomeofthecommonlyusedmodulesinthislibrary.YoucanfindcompletedetailsforallofthemodulesinthePythonStandardLibrary in the ‘Library Reference’ section of the documentation that comes with yourPythoninstallation.
sysmodule
The sys module contains system-specific functionality. We have already seen that thesys.argv listcontains thecommand-linearguments.Forexample,youwant tocheck theversionofthePythonsoftwarebeingused;thesysmodulegivesusthatinformation.
$python
>>>importsys
>>>sys.version_info
sys.version_info(major=2,minor=7,micro=6,releaselevel=‘final’,serial=0)
>>>sys.version_info.major==2
True
loggingmodule
Whatifyouwantedtohavesomedebuggingmessagesorimportantmessagestobestoredsomewheresothatyoucancheckwhetheryourprogramhasbeenrunningasyouwouldexpectit?Howdoyou“storesomewhere”thesemessages?Thiscanbeachievedusingtheloggingmodule.
Saveasstdlib_logging.py:
importos,platform,logging
ifplatform.platform().startswith(‘Windows’):
logging_file=os.path.join(os.getenv(‘HOMEDRIVE’),
os.getenv(‘HOMEPATH’),
‘test.log’)
![Page 17: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/17.jpg)
else:
logging_file=os.path.join(os.getenv(‘HOME’),‘test.log’)
print“Loggingto”,logging_file
logging.basicConfig(
level=logging.DEBUG,
format=’%(asctime)s:%(levelname)s:%(message)s’,
filename=logging_file,
filemode=‘w’,
)
logging.debug(“Startoftheprogram”)
logging.info(“Doingsomething”)
logging.warning(“Dyingnow”)
Output:
$pythonstdlib_logging.py
Loggingto/Users/swa/test.log
$cat/Users/swa/test.log
2014-03-2909:27:36,660:DEBUG:Startoftheprogram
2014-03-2909:27:36,660:INFO:Doingsomething
2014-03-2909:27:36,660:WARNING:Dyingnow
CREATINGCLASSES&OBJECTS
Pythonisanobject-orientedlanguageandbecauseofthiscreatingandusingclassesandobjectsarequiteeasy.
OverviewofOOPTerminologyClass: A user-defined prototype for an object that defines a set of attributes thatcharacterize any object of the class. The attributes are data members and methods,accessedviadotnotation.
Classvariable:Avariable that is sharedbyall instancesof a class.Classvariablesaredefinedwithinaclassbutoutsideanyoftheclass’smethods.Classvariablesaren’tusedasfrequentlyasinstancevariablesare.
Datamember:Aclassvariableorinstancevariablethatholdsdataassociatedwithaclass
![Page 18: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/18.jpg)
anditsobjects.
Function overloading: The assignment of more than one behavior to a particularfunction.Theoperationperformedvariesbythetypesofobjectsinvolved.
Instance variable: A variable that is defined inside amethod and belongs only to thecurrentinstanceofaclass.
Inheritance:Thetransferofthecharacteristicsofaclasstootherclassesthatarederivedfromit.
Instance:Anindividualobjectofacertainclass.Anobject‘obj’ thatbelongs toaclassCircle,forexample,isaninstanceoftheclassCircle.
Instantiation:Thecreationofaninstanceofaclass.
Method:Aspecialkindoffunctionthatisdefinedinaclassdefinition.
Object: A unique instance of a data structure that’s defined by its class. An objectcomprisesbothdatamembersandmethods.
Operator overloading: The assignment of more than one function to a particularoperator.
DOCUMENTINGYOURCODE
To document a Python object, docstring is used. A docstring is simply a triple-quotedsentence which gives a brief summary of the object. The object can be anything afunction,amethod,aclass,etc.
Anythingwritten in the triplequotes is the function’sdocstring,whichdocumentswhatthefunctiondoes.Adocstring,isthefirstthingthatisdefinedinafunction.Docstringisavailable at runtime as an attribute of the function.The docstring of a script should beusableasits‘usage’message,printedwhenthescriptisinvokedwithincorrectormissingarguments.Thedocstringisaphraseendinginaperiod.Itdescribesthefunction’seffectasacommand.
![Page 19: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/19.jpg)
In docstring for a module classes, exceptions and functions that are exported by themodule are listed. The docstring for a function or method summarize its behavior anddocumentitsarguments,returnvalue(s),sideeffectsandexceptionsraised.Thedocstringfor a class summarize its behavior and list the public methods and instance variables.Individualmethodsshouldbedocumentedbytheirowndocstring.
You can add a docstring to a function, class, ormodule by adding a string as the firstindentedstatement.
Forexample:
#!/usr/bin/envpython
#docstringexample.py
“““Exampleofusingdocumentationstrings.”””
classKnight:
”””
Anexampleclass.
Callspamtogetbacon.
”””
defspam(eggs=“bacon”):
“““Printstheargumentgiven.”””
print(eggs)
PYTHON-OBJECTORIENTEDPROGRAMMING
LearningPythonClassesInOOP (object-oriented programming), the class is themost basic component.OOP isverypowerful toolandmanyPython librariesandAPIsusesclasses,andsoyoushouldknowwhatclassesare?Howtheywork?Andhowtocreatethem?OnethingtorememberaboutPythonandOOPisthatit’snotmandatorytouseobjectsinyourcode.
![Page 20: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/20.jpg)
NowthequestionishowareClassesBetter?Let’s take an example, suppose you want to calculate the velocity of a car in a two-dimensionalplaneusingfunctions.Andyounowwanttomakeanewprogramtocalculatethevelocityofanairplaneinthreedimensions,andthenyou’llhavetorewritethemanyofthefunctionstomakethemworkfortheverticaldimension,especiallytomaptheobjectina3-Dspace. In thatcaseclassesareused.Classes letyoudefineanobjectonce,andthenyoucanreuseitmultipletimes.Youneedtogiveitabasefunction,andthenbuilduponthatmethodtoredefineitasnecessary.
ImprovingYourClassStandingSomeconceptsofclassesaregivenbelow.Havealookatthem:
-Classeshaveadefinitenamespace,justlikemodules.Tryingtocallaclassmethodfromadifferentclasswillgiveyouanerrorunlessyouqualifyit,e.g.spamClass.eggMethod().
- Classes supportmultiple copies. Classes have two different objects: class objects andinstanceobjects.Classobjectsareusedtogivethedefaultbehaviorandareusedtocreateinstance objects. Instance objects are the objects that actually do the work in yourprogram.Youcanhaveasmanyinstanceobjectsofthesameclassobjectasyouneed.
-Eachinstanceobjecthasitsownnamespacebutalsoinheritsfromthebaseclassobject.Thismeanseachinstancehasthesamedefaultnamespacecomponentsastheclassobject,butadditionallyeachinstancecanmakenewnamespaceobjectsjustforitself.
-Classescandefineobjectsthatrespondtothesameoperationsasbuilt-intypes.So,classobjects can be sliced, indexed, con- catenated, etc. just like strings, lists, and otherstandardPythontypes.ThisisbecauseeverythinginPythonisactuallyaclassobject;wearen’tactuallydoinganythingnewwithclasses,we’rejustlearninghowtobetterusetheinherentnatureofthePythonlanguage.
SoWhatDoesaClassLookLike?Seehereyouclasslooklikeinpython:
Definingaclass
>>>classItem:#defineaclassobject
…defsetName(self,value):#defineclassmethods
…self.name=value#selfidentifiesaparticularinstance
![Page 21: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/21.jpg)
…defdisplay(self):
…printself.name#printthedataforaparticularinstance
Creatingclassinstances>>>x=Item()
>>>y=Item()
>>>z=Item()
Addingdatatoinstances>>>x.setName(“Hello,ThisisPythonbook.”)
>>>y.setName(“Iamaquicklearner.”)
>>>z.setName(“Itisworthbuyingthisbook.”)
Displayinginstancedata>>>x.display()
Hello,ThisisPythonbook.
>>>y.display()
Iamaquicklearner.
>>>z.display()
Itisworthbuyingthisbook.
PYTHONDATABASES
Inpythonwhenyouusewebapplicationsorcustomer-orientedprograms,Databasesareveryimportant.Normalfiles,suchastextfiles,areeasytocreateanduse;Pythonhasthe
![Page 22: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/22.jpg)
toolsbuilt-inand itdoesn’t takemuch toworkwith files.Databasesareusedwhenyouworkon discrete “structures”, such as customer list that has phone numbers, addresses,pastorders,etc.databaseisusedtostorealumpofdataanditallowstheuserordevelopertopullthenecessaryinformation,withoutregardtohowthedataisstored.Also,databasescanbeusedtoretrievedatarandomly,ratherthansequentially.
HowtoUseaDatabase
Adatabaseisacollectionofdata,whichisplacedintoanarbitrarystructuredformat.Mostcommonlyuseddatabaseisarelationaldatabase.Indatabasetablesareusedtostorethedata and relationships can be defined between different tables. SQL (Structured QueryLanguage)isthelanguagewhichisusedtoworkwithmostDatabases.SQLprovidesthecommands to query a database and retrieve ormanipulate the information. SQL is alsousedtoinputinformationintoadatabase.
WorkingWithADatabase
Database consists of one or more tables, just like a spreadsheet. The vertical columnscompriseofdifferentfieldsorcategories;theyareanalogoustothefieldsyoufilloutinaform.Thehorizontalrowsareindividualrecords;eachrowisonecompleterecordentry.Hereisanexamplerepresentingacustomer’slist.
USINGSQLTOQUERYADATABASE
Here,Indexfieldistheonethatprovidesauniquevaluetoeveryrecord;it’softencalledtheprimarykeyfield.Theprimarykeyisaspecialobjectfordatabases;simplyidentifyingwhichfield is theprimarykeywillautomatically increment that fieldasnewentriesaremade, therebyensuringauniquedataobject foreasy identification.Theother fieldsaresimplycreatedbasedontheinformationthatyouwanttoincludeinthedatabase.
Nowifyouwanttomakeorderentrydatabase,andwanttolinkthattotheabovecustomerlist,soitshouldbelike:
![Page 23: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/23.jpg)
Thistableiscalled“Orders_table”.Thistableshowsvariousordersmadebyeachpersoninthecustomer table.EachentryhasauniquekeyandisrelatedtoCustomers_tablebytheCustomer_IDfield,whichistheIndexvalueforeachcustomer.
PythonandSQLite
PythonhasaSQLite,alight-weightSQLlibrary.SQLiteisbasicallywritteninC,soitisveryquickandeasytounderstand.Itcreatesthedatabaseinasinglefile,soimplementingadatabasebecomes fairlysimple;youdon’tneed toworryabout the issuesofhavingadatabase spread across a server.SQLite is good for prototypingyour applicationbeforeyouthrowinafull-blowndatabase.Bythisyoucaneasilyknowhowyourprogramworksand any problems aremost likelywith the database implementation. It’s also good forsmallprogramsthatdon’tneedacompletedatabasepackagewithitsassociatedoverhead.
CreatinganSQLitedatabase
SQLite isbuilt intoPython, so it caneasilybe imported toanyother library.Onceyouimportit,youhavetomakeaconnectiontoit;soastocreatethedatabasefile.CursorinSQLiteperformsmostofthefunctions;youwillbedoingwiththedatabase.
importsqlite3#SQLitev3istheversioncurrentlyincludedwithPython
connection=sqlite3.connect(“Hand_tools.database”)#The.databaseextensionisoptional
cursor=connection.cursor()
#Alternativedatabasecreatedonlyinmemory
#mem_conn=sqlite3.connect(“:memory:”)
#cursor=mem_conn.cursor()
cursor.execute(“““CREATETABLETools(idINTEGERPRIMARYKEY,nameTEXT,sizeTEXT,priceINTEGER)”””)
foritemin((None,“Book”,“Small”,15),#Theendcommaisrequiredtoseparate
![Page 24: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/24.jpg)
tuple items (None,“Purse”,“Medium”,35),(None,“Pen”,“Large”,55),(None,”Hat”,“Small”,25),(None,“Handbag”,“Small”,25),(None,“Socks”,“Small”,10),(None,“Comb”,“Large”,60),):cursor.execute (“INSERT INTO Tools VALUES(?,?,?,?)”,item)
connection.commit()#Writedatatodatabase
cursor.close()#Closedatabase
Inthisexamplequestionmarks(?)areusedtoinsertitemsintothetable.Theyareusedtoprevent a SQL injection attack, where a SQL command is passed to the database as alegitimatevalue.Thequestionmarksactasasubstitutionvalue.
RetrievingdatafromSQLite
ToretrievethedatafromaSQLitedatabase,youjustusetheSQLcommandsthattellthedatabasewhatinformationyouwantandhowyouwantitformatted.
Example:
cursor.execute(“SELECTname,size,priceFROMTools”)
toolsTuple=cursor.fetchall()
fortupleintoolsTuple:name,size,price=tuple#unpackthetuples
item=(“%s,%s,%d”%(name,size,price))
printitem
Output:
Book,Small,15
Purse,Medium,35
Pen,Large,55
Hat,Small,25
Handbag,Small,25
Socks,Small,10
Comb,Large,60
Book,Small,15
Purse,Medium,35
Pen,Large,55
Hat,Small,25
![Page 25: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/25.jpg)
Handbag,Small,25
Socks,Small,10
Comb,Large,60
Dealingwithexistingdatabases
SQLite will try to recreate the database file every time you run the program. If thedatabasefilealreadyexists,youwillgetan“OperationalError”exceptionstatingthatthefilealreadyexists.Theeasiestwaytodealwiththisistosimplycatchtheexceptionandignoreit.
cursor.execute(“CREATETABLEFoo(idINTEGERPRIMARYKEY,nameTEXT)”)
exceptsqlite3.OperationalError:pass
Thiswillallowyoutorunyourdatabaseprogrammultipletimeswithouthavingtodeletethedatabasefileaftereveryrun.
CLASSES
Classisadatastructurethatisusedinpythontodefineobjects,whichholdsdatavaluesand behavioral characteristics. Classes are the entities, which are the programs of anabstraction for aproblem,and instancesare realizationsof suchobjects.The termmostlikely originates from using classes to identify and categorize biological families ofspecies to which specific creatures belong and can be derived into similar yet distinctsubclasses.Manyofthesefeaturesapplytotheconceptofclassesinprogramming.
InPython, classdeclarations are similar to the functiondeclarations, a header linewithappropriatekeywordfollowedbyasuiteasitsdefinition,asindicatedbelow:
deffunctionName(args):
‘functiondocumentationstring’
function_suite
class
ClassName:
‘classdocumentationstring’
class_suite
![Page 26: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/26.jpg)
Classinpythonholdsmultipledataitems,anditcanalsosupportitsownsetoffunctions,which are calledmethods.Youmaybe askingwhat other advantages classeshaveoverstandardcontainertypessuchaslistsanddictionaries.
CreatingClassesPython classes are created using the class keyword. In the simple form of classdeclarations,thenameoftheclassimmediatelyfollowsthekeyword:
classClassName:
‘classdocumentationstring’
class_suite
class_suite consists of all the component statements, defining class members, dataattributes,andfunctions.Classesaregenerallydefinedatthetop-levelofamodulesothatinstancesofaclasscanbecreatedanywhereinapieceofsourcecodewheretheclassisdefined.
ClassDeclarationvs.DefinitionIn python there is no difference in declaring and defining classes because they occursimultaneously.Thedefinitionfollowsthedeclarationandthedocumentationstring.
ClassAttributesAclassattributeisafunctionalelement,whichbelongstoanotherobjectandisaccessedviadotted-attributenotation.InPython,complexnumbershavedataattributeswhilelistsanddictionarieshavefunctionalattributes.Whenyouaccessattribute,youcanalsoaccessanobjectthatmayhaveattributesofitsown.
Forexample:
-sys.stdout.write(‘abc’)
-printmyModule.myClass.__doc__
-myList.extend(map(upper,open(‘x’).readlines()))
![Page 27: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/27.jpg)
Classattributesarelinkedtotheclassesinwhichtheyaredefined,andinstanceobjectsarethemost commonly used objects in OOP. Instance data attributes are the primary dataattributes thatareused.Classdataattributesareusefulonlywhena“static”data typeisrequired,whichdoesnotrequireanyinstances.
ClassDataAttributesDataattributesarethevariablesoftheclasswhicharedefinedbytheprogrammer.Theycan be used like any other variable when the class is created and can be updated bymethodswithin theclass.These typesof attributes arebetterknown toprogrammersasstaticmembers,classvariables,orstaticdata.Theyrepresentdatathatistiedtotheclassobjecttheybelongtoandareindependentofanyclassinstances.
Exampleofusingclassdataattributes(abc):
>>>classC:
…abc=100
>>>printC.abc
0
>>>C.abc=C.abc+1
>>>printC.abc
Output:
101
METHODS
In the example given below,MyFirstMethodmethod of theMyTeam class is simply afunctionwhichisdefinedaspartofaclassdefinition.ThismeansthatMyMethodappliesonlytoobjectsorinstancesofMyTeamtype.
ForExample:
>>>classMyTeam:
defMyFirstMethod(self):
pass
>>>myInstance=MyTeam()
![Page 28: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/28.jpg)
>>>myInstance.MyFirstMethod()
AnycalltoMyFirstMethodbyitselfasafunctionfails:
>>>MyFirstMethod()
Traceback(innermostlast):
File“<stdin>”,line1,in?
MyFirstMethod()
NameError:MyFirstMethod
Here in the above example, NameError exception is raised because there is no suchfunction in the global namespace. Here MyFirstMethod is a method, meaning that itbelongs to the class and is not a name in theglobal namespace. IfMyFirstMethodwasdefinedasafunctionatthetop-level,thenourcallwouldhavesucceeded.Weshowyoubelowthatevencallingthemethodwiththeclassobjectfails.
>>>MyTeam.MyFirstMethod()
Traceback(innermostlast):
File“<stdin>”,line1,in?
MyTeam.MyFirstMethod()
TypeError:unboundmethodmustbecalledwithclassinstance1stargument
ThisTypeErrorexceptionmayseemperplexingatfirstbecauseyouknowthatthemethodisanattributeoftheclassandsoarewonderingwhythereisafailure.
StaticMethodsPythondoesnot support staticmethods, and functionswhichareassociatedonlywithaclassandnotwithanyparticularinstances.Theyareeitherfunction,whichhelpmanagestaticclassdataorareglobalfunctionswhichhavesomesortoffunctionalityrelatedtotheclass, inwhich they are defined.Because python does not support staticmethods, so astandardglobalfunctionisrequired.
![Page 29: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/29.jpg)
INSTANCES
Classisadatastructuredefinitiontype,whileaninstanceisadeclarationofavariableofthattype.Oryoucansaythatinstancesareclasseswhicharebroughttolife.Instancesarethe objects which are used primarily during execution, and all instances are of type“instance.”
CreatingInstancesbyInvokingClassObjectMost languages provide a new keyword to create an instance of a class. The python’sapproachismuchsimpler.Onceaclasshasbeendefinedinpython,creatinganinstanceisnomoredifficult.Usinginstantiationofthefunctionoperator.
ForExample:
>>>classMyTeam:#defineclass
…pass
>>>myInstance=MyTeam()#instantiateclass
>>>type(MyTeam)#classisofclasstype
<type‘class’>
>>>type(myInstance)#instanceisofinstancetype
<type‘instance’>
Usingtheterm“type”inPythonisdifferentfromtheinstancebeingofthetypeofclassitwascreatedfrom.Anobject’stypedictatesthebehavioralpropertiesofsuchobjectsinthePython system, and these types are a subset of all types,whichPython supports.User-defined “types” such as classes are categorized in the samemanner. Classes share thesametype,buthavedifferentIDsandvalues.Allclassesaredefinedwiththesamesyntax,so they can be instantiated, and all have the same core properties. Classes are uniqueobjects,whicharedifferonlyindefinition,hencetheyareallthesame“type”inPython.
![Page 30: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/30.jpg)
InstanceAttributesInstanceshaveonlydataattributesandthesearesimplythedatavalueswhichyouwanttobeassociatedwithaparticularinstanceofanyclass.Theyareaccessibleviathefamiliardotted-attributenotation.Thesevaluesareindependentofanyotherinstanceortheclassitwas instantiated from. If any instance is deallocated, then its attributes are alsodeallocated.
“Instantiating”InstanceAttributesInstanceattributescanbesetanytimeafteraninstancehasbeencreated,inanypieceofcodethathasaccesstotheinstance.However,oneofthekeyplaceswheresuchattributesaresetisintheconstructor,__init__().
ConstructorFirstPlacetoSetInstanceAttributesTheconstructoristheearliestplacethatinstanceattributescanbesetbecause__init__()is the first method called after instance objects have been created. There is no earlieropportunitytosetinstanceattributes.Once__init__()hasfinishedexecution,theinstanceobjectisreturned,completingtheinstantiationprocess.
DefaultArgumentsProvideDefaultInstanceSetupOnecanalsouse__init__()alongwithdefaultargumentstoprovideaneffectivewayinpreparinganinstanceforuse.Inmostofthecases,thedefaultvaluesrepresentthemostcommoncasesforsettingupinstanceattributes,andsuchuseofdefaultvaluesprecludesthemfromhavingtobegivenexplicitlytotheconstructor.
Built-inTypeAttributesBuilt-in types also have attributes, and although they are technically not class instanceattributes,theyaresufficientlysimilartogetabriefmentionhere.Typeattributesdonothaveanattributedictionarylikeclassesandinstances(__dict__),sohowdowefigureoutwhatattributesbuilt-intypeshave?Theconventionforbuilt-intypesistousetwospecialattributes,__methods__and__members__,tooutlineanymethodsand/ordataattributes.
InstanceAttributesvs.ClassAttributesClassattributesaresimplydatavalueswhichareassociatedwithaclassandwithnotany
![Page 31: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/31.jpg)
particular instances. Such values are also referred to as static members because theirvaluesremainconstant,evenifaclassisinvokedduetoinstantiationmultipletimes.Nomatter what, static members maintain their values independent of instances unlessexplicitly changed. Comparing instance attributes to class attributes is just similar tocomparingautomaticandstaticvariables.Theirmainaspectisthatyoucanaccessaclassattributewitheithertheclassoraninstance,whiletheinstancedoesnothaveanattributewiththesamename.
PythonDatabaseAccess
ThestandarddatabaseusedforPythonisDB-API.MostPythondatabaseinterfacesadheretothisstandard.Youcanchoosetherightdatabaseforyourapplication.PythonDatabaseAPI supports a wide range of database servers such as, GadFly, mSQL, MySQL,PostgreSQL,MicrosoftSQLServer11000,Informix,Interbase,Oracle,Sybase.Youmustdownload a separate DB API module for each database that you need to access. Forexample,ifyouneedtoaccessanOracledatabaseaswellasaMySQLdatabase,thenyouneedtodownloadboththeOracleandtheMySQLdatabasemodules.
The DB API provides a minimal standard for working with databases using Pythonstructuresandsyntaxwhereverpossible.
TheAPIincludes:
•ImportingtheAPImodule.
•Acquiringaconnectionwiththedatabase.
•IssuingSQLstatementsandstoredprocedures.
•Closingtheconnection
![Page 32: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/32.jpg)
WewouldlearnalltheconceptsusingMySQL,solet’stalkaboutMySQLdbmoduleonly.
WhatisMySQLdb?MySQLdb is an interface for connecting to aMySQL database server from Python. ItimplementsthePythonDatabaseAPIv2.0andisbuiltontopoftheMySQLCAPI.
HowtoinstallMySQLdb?Beforeproceeding,youmakesureyouhaveMySQLdb installedonyourTomhine. JusttypethefollowinginyourPythonscriptandexecuteit:
#!/usr/bin/python
importMySQLdb
Ifitproducesthefollowingresult,thenitmeansMySQLdbmoduleisnotinstalled:
Traceback(mostrecentcalllast):
File“test.py”,line3,in<module>
importMySQLdb
ImportError:NomodulenamedMySQLdb
ToinstallMySQLdbmodule,downloaditfromMySQLdbDownloadpageandproceedasfollows:
$gunzipMySQL-python-1.2.2.tar.gz
$tar-xvfMySQL-python-1.2.2.tar
$cdMySQL-python-1.2.2
$pythonsetup.pybuild
$pythonsetup.pyinstall
DatabaseConnection:BeforeconnectingtoaMySQLdatabase,youneedtomakesureofthefollowingspointsgivenbelow:
•YouhavecreatedadatabaseTESTDB.
•YouhavecreatedatableSTAFFinTESTDB.
![Page 33: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/33.jpg)
•ThistableishavingfieldsFIRST_NAME,LAST_NAME,AGE,SEXandINCOME.
•UserID“abctest”andpassword“python121”aresettoaccessTESTDB.
•PythonmoduleMySQLdbisinstalledproperlyonyourTomhine.
•YouhavegonethroughMySQLtutorialtounderstandMySQLBasics.
ForExample:
ConnectingwithMySQLdatabase“TESTDB”:
#!/usr/bin/python
importMySQLdb
#Opendatabaseconnection
db=MySQLdb.connect(“localhost”,“abctest”,“python121”,“TESTDB”)
#prepareacursorobjectusingcursor()method
cursor=db.cursor()
#executeSQLqueryusingexecute()method.
cursor.execute(“SELECTVERSION()”)
#Fetchasinglerowusingfetchone()method.
data=cursor.fetchone()
print“Databaseversion:%s”%data
#disconnectfromserver
db.close()
Output:
Databaseversion:5.0.45
CreatingDatabaseTable:
Onceadatabaseconnectionisestablished,youcaneasilycreatetablesorrecordsintothedatabaseusingexecutemethod.
ExampleforcreatingDatabasetableSTAFF:
#!/usr/bin/python
importMySQLdb
![Page 34: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/34.jpg)
#Opendatabaseconnection
db=MySQLdb.connect(“localhost”,“abctest”,“python121”,“TESTDB”)
#prepareacursorobjectusingcursor()method
cursor=db.cursor()
#Droptableifitalreadyexistusingexecute()method.
cursor.execute(“DROPTABLEIFEXISTSSTAFF”)
# Create table as per requirement sql = “““CREATE TABLE STAFF (FIRST_NAMECHAR(20) NOT NULL,LAST_NAME CHAR(20),AGE INT,SEX CHAR(1),INCOMEFLOAT)”””
cursor.execute(sql)
#disconnectfromserver
db.close()
INSERTOperation:INSERToperationisrequiredwhenyouwanttocreateyourrecordsintoadatabasetable.
ExampletocreatearecordintoSTAFFtable:
#!/usr/bin/python
importMySQLdb
#Opendatabaseconnection
db=MySQLdb.connect(“localhost”,“abctest”,“python121”,“TESTDB”)
#prepareacursorobjectusingcursor()method
cursor=db.cursor()
#PrepareSQLquerytoINSERTarecordintothedatabase.
sql=“““INSERTINTOSTAFF(FIRST_NAME,LAST_NAME,AGE,SEX,INCOME)
VALUES(‘Tom’,‘David’,20,‘M’,11000)”””
try:
#ExecutetheSQLcommand
cursor.execute(sql)
#Commityourchangesinthedatabase
db.commit()
except:
#Rollbackincasethereisanyerror
![Page 35: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/35.jpg)
db.rollback()
#disconnectfromserver
db.close()
AboveexamplecanbewrittenasfollowstocreateSQLqueriesdynamically:
#!/usr/bin/python
importMySQLdb
#Opendatabaseconnection
db=MySQLdb.connect(“localhost”,“abctest”,“python121”,“TESTDB”)
#prepareacursorobjectusingcursor()method
cursor=db.cursor()
#PrepareSQLquerytoINSERTarecordintothedatabase.
sql=“INSERTINTOSTAFF(FIRST_NAME,\LAST_NAME,AGE,SEX,INCOME)\
VALUES(‘%s’,‘%s’,‘%d’,‘%c’,‘%d’)”%\(‘Tom’,‘David’,20,‘M’,11000)
try:
#ExecutetheSQLcommand
cursor.execute(sql)
#Commityourchangesinthedatabase
db.commit()
except:
#Rollbackincasethereisanyerror
db.rollback()
#disconnectfromserver
db.close()
READOperation:READOperationondatabasemeanstofetchsomeusefulinformationfromthedatabase.Once our database connection is established, we are ready to make a query into thisdatabase.Wecanuseeitherfetchone()methodtofetchsinglerecordorfetchall()methodtofetechmultiplevaluesfromadatabasetable.
• fetchone(): Thismethod fetches the next row of a query result set.A result set is anobjectthatisreturnedwhenacursorobjectisusedtoqueryatable.
• fetchall():Thismethod fetchesall the rows ina result set. If somerowshavealready
![Page 36: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/36.jpg)
beenextractedfromtheresultset,thefetchall()methodretrievestheremainingrowsfromtheresultset.
• rowcount: This is a read-only attribute and returns the number of rows that wereaffectedbyanexecute()method.
ExampletoqueryalltherecordsfromSTAFFtablehavingsalarymorethan5000:
#!/usr/bin/python
importMySQLdb
#Opendatabaseconnection
db=MySQLdb.connect(“localhost”,“abctest”,“python121”,“TESTDB”)
#prepareacursorobjectusingcursor()method
cursor=db.cursor()
#PrepareSQLquerytoINSERTarecordintothedatabase.
sql=“SELECT*FROMSTAFF\
WHEREINCOME>‘%d’”%(1000)
try:
#ExecutetheSQLcommand
cursor.execute(sql)
#Fetchalltherowsinalistoflists.
results=cursor.fetchall()
forrowinresults:
fname=row[0]
lname=row[1]
age=row[2]
sex=row[3]
income=row[4]
#Nowprintfetchedresult
print“fname=%s,lname=%s,age=%d,sex=%s,income=%d”%\
(fname,lname,age,sex,income)
except:
print“Error:unabletofecthdata”
#disconnectfromserver
db.close()
![Page 37: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/37.jpg)
Output:
fname=Tom,lname=David,age=20,sex=M,income=11000
UpdateOperation:UPDATEOperation on any database means to update one or more records, which arealready available in the database. Following is the procedure to update all the recordshavingSEXas‘M’.Here,wewillincreaseAGEofallthemalesbyoneyear.
ForExample:
#!/usr/bin/python
importMySQLdb
#Opendatabaseconnection
db=MySQLdb.connect(“localhost”,“abctest”,“python121”,“TESTDB”)
#prepareacursorobjectusingcursor()method
cursor=db.cursor()
#PrepareSQLquerytoUPDATErequiredrecords
sql=“UPDATESTAFFSETAGE=AGE+1
WHERESEX=‘%c’”%(‘M’)
try:
#ExecutetheSQLcommand
cursor.execute(sql)
#Commityourchangesinthedatabase
db.commit()
except:
#Rollbackincasethereisanyerror
db.rollback()
#disconnectfromserver
db.close()
DELETEOperation:
![Page 38: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/38.jpg)
DELETEoperationisrequiredwhenyouwanttodeletesomerecordsfromyourdatabase.FollowingistheproceduretodeletealltherecordsfromSTAFFwhereAGEismorethan20:
ForExample:
#!/usr/bin/python
importMySQLdb
#Opendatabaseconnection
db=MySQLdb.connect(“localhost”,“abctest”,“python121”,“TESTDB”)
#prepareacursorobjectusingcursor()method
cursor=db.cursor()
#PrepareSQLquerytoDELETErequiredrecords
sql=“DELETEFROMSTAFFWHEREAGE>‘%d’”%(20)
try:
#ExecutetheSQLcommand
cursor.execute(sql)
#Commityourchangesinthedatabase
db.commit()
except:
#Rollbackincasethereisanyerror
db.rollback()
#disconnectfromserver
db.close()
PerformingTransactions:Transactionsareamechanismthatensuresconsistencyofdata.Transactionsshouldhavethefollowingproperties:
•Atomicity:Eitheratransactioncompletesornothinghappensatall.
•Consistency: A transactionmust start in a consistent state and leave the system in aconsistentstate.
• Isolation: Intermediate results of a transaction are not visible outside the currenttransaction.
•Durability:Once a transactionwas committed, the effects are persistent, even after a
![Page 39: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/39.jpg)
systemfailure.
ThePythonDBAPI2.0providestwomethodstoeithercommitorrollbackatransaction.
ForExample:
#PrepareSQLquerytoDELETErequiredrecords
sql=“DELETEFROMSTAFFWHEREAGE>‘%d’”%(20)
try:
#ExecutetheSQLcommand
cursor.execute(sql)
#Commityourchangesinthedatabase
db.commit()
except:
#Rollbackincasethereisanyerror
db.rollback()
COMMITOperation:Commit is theoperation,whichgivesagreensignal todatabase tofinalize thechanges,andafterthisoperation,nochangecanberevertedback.
ForExample:
db.commit()
ROLLBACKOperation:Ifyouarenotsatisfiedwithoneormoreofthechangesandyouwanttorevertbackthosechangescompletely,thenuserollback()method.
ForExample:
db.rollback()
DisconnectingDatabase:TodisconnectDatabaseconnection,useclose()method.
![Page 40: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/40.jpg)
ForExample:
db.close()
If the connection to a database is closed by the user with the close() method, anyoutstandingtransactionsarerolledbackbytheDB.However,insteadofdependingonanyofDB lower level implementation details, your applicationwould be better off callingcommitorrollbackexplicitly.
HandlingErrors:Therearemanysourcesoferrors.AfewexamplesareasyntaxerrorinanexecutedSQLstatement, a connection failure, or calling the fetchmethod for an already canceled orfinishedstatementhandle.TheDBAPIdefinesanumberoferrorsthatmustexistineachdatabasemodule.Thefollowingtableliststheseexceptions.
ExceptionDescription
WarningUsedfornon-fatalissues.MustsubclassStandardError.
ErrorBaseclassforerrors.MustsubclassStandardError.
InterfaceError
Usedforerrorsinthedatabasemodule,notthedatabaseitself.MustsubclassError.
DatabaseError
Usedforerrorsinthedatabase.MustsubclassError.DataErrorSubclassofDatabaseErrorthatreferstoerrorsinthedata.
OperationalError
Subclass of DatabaseError that refers to errors such as the loss of a connection to thedatabase.TheseerrorsaregenerallyoutsideofthecontrolofthePythonscripter.
IntegrityError
SubclassofDatabaseErrorforsituationsthatwoulddamagetherelationalintegrity,suchasuniquenessconstraintsorforeignkeys.
![Page 41: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/41.jpg)
InternalError
SubclassofDatabaseErrorthatreferstoerrorsinternaltothedatabasemodule,suchasacursornolongerbeingactive.
ProgrammingError
SubclassofDatabaseErrorthatreferstoerrorssuchasabadtablenameandotherthingsthatcansafelybeblamedonyou.
NotSupportedError
SubclassofDatabaseErrorthatreferstotryingtocallunsupportedfunctionality.
Your Python scripts should handle these errors, but before using any of the aboveexceptions,makesureyourMySQLdbhassupportfor thatexception.YoucangetmoreinformationaboutthembyreadingtheDBAPI2.0specification.
PYTHONNETWORKING
Pythonprovidestwolevelsofaccesstonetworkservices.Atalowlevel,youcanaccessthe basic socket support in the underlying operating system which allows you toimplementclientsandserversforbothconnectionorientedandconnectionlessprotocols.Python also has libraries that provide higher-level access to specific application-levelnetworkprotocols,suchasFTP,HTTP,andsoon.
WhatareSockets?Sockets are the endpoints of a bidirectional communications channel. Sockets maycommunicate within a process, between processes on the same machine, or betweenprocessesondifferentcontinents.Socketsmaybeimplementedoveranumberofdifferentchanneltypes:UNIXdomainsockets,TCP,UDP,andsoon.Thesocketlibraryprovidesspecific classes for handling the common transports as well as a generic interface forhandlingtherest.
Socketshavetheirownvocabulary:
![Page 42: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/42.jpg)
ThesocketModule:Tocreateasocket,youmustusethesocket.socket()functionavailableinsocketmodule.Syntax:
s=socket.socket(socket_family,socket_type,protocol=0)
Descriptionofparameters:
•socket_family:ThisiseitherAF_UNIXorAF_INET,asexplainedearlier.
•socket_type:ThisiseitherSOCK_STREAMorSOCK_DGRAM.
•protocol:Thisisusuallyleftout,defaultingto0.
Socketobjectsareuserequiredfunctionstocreateyourclientorserverprogram.HereIamgoingtosharewithyouthelistoffunctionsrequired:
ServerSocketMethods:
ClientSocketMethods:
GeneralSocketMethods:
![Page 43: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/43.jpg)
ASimpleServer:TowriteInternetservers,weusethesocketfunctionavailableinsocketmoduletocreateasocketobject.Asocketobjectisthenusedtocallotherfunctionstosetupasocketserver.Now,callbind (hostname,port) function tospecifyaport foryourserviceon thegivenhost.
Next, call the accept method of the returned object. This method waits until a clientconnectstotheportyouspecifiedandthenreturnsaconnectionobjectthatrepresentstheconnectiontothatclient.
Example:
#!/usr/bin/python#Thisisserver.pyfile
importsocket#Importsocketmodule
s=socket.socket()#Createasocketobject
host=socket.gethostname()#Getlocalmachinename
port=102#Reserveaportforyourservice.
s.bind((host,port))#Bindtotheport
s.listen(5)#Nowwaitforclientconnection.
whileTrue:
c,addr=s.accept()#Establishconnectionwithclient.
print‘Gotconnectionfrom’,addr
c.send(‘Thanksforconnecting’)
c.close()#Closetheconnection
ASimpleClient:Now,wewillwriteaverysimpleclientprogram,whichwillopenaconnectiontoagivenport102andgivenhost.ThisisverysimpletocreateasocketclientusingPython’ssocketmodulefunction.Thesocket.connect(hosname,port)opensaTCPconnectiontohostnameontheport.Onceyouhaveasocketopen,youcanreadfromitlikeanyIOobject.When
![Page 44: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/44.jpg)
done,remembertocloseit,asyouwouldcloseafile.Thefollowingcodeisaverysimpleclientthatconnectstoagivenhostandport,readsanyavailabledatafromthesocket,andthenexits:
Example:
#!/usr/bin/python#Thisisclient.pyfile
importsocket#Importsocketmodule
s=socket.socket()#Createasocketobject
host=socket.gethostname()#Getlocalmachinename
port=102#Reserveaportforyourservice.
s.connect((host,port))
prints.recv(1024)
s.close#Closethesocketwhendone
Now,runthisserver.pyinbackgroundandthenrunaboveclient.pytoseetheresult.
#Followingwouldstartaserverinbackground.
$pythonserver.py&
#Onceserverisstartedrunclientasfollows:
$pythonclient.py
Output:
Gotconnectionfrom(‘127.0.0.1’,48437)
Thanksforconnecting
PythonInternetmodulesHere below is a list of some important modules, which are used in PythonNetwork/Internetprogramming.
![Page 45: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/45.jpg)
SENDINGMAILINPYTHON
Simple Mail Transfer Protocol (SMTP) is a protocol that is used to send e-mails androuting e-mails between the mail servers. In Python there is ‘smtplib’ module, whichdefinesanSMTPclientsessionobject.SMTPclientsessionobjectisusedtosendmailtoanyInternetmachinewithanSMTPorESMTPlistenerdaemon.
SYNTAX:
importsmtplib
smtpObj=smtplib.SMTP([host[,port[,local_hostname]]])
Detailofparametersused:
•host:ThisisthehostrunningyourSMTPserver.YoucanspecifyIPaddressofthehostoradomainname.Thisisoptionalargument.
•port:Ifyouareprovidinghostargument,thenyouneedtospecifyaport,whereSMTPserverislistening.Usuallythisportwouldbe25.
•local_hostname: IfyourSMTPserver is runningonyour localmachine, thenyoucanspecify justlocalhost as of this option. An SMTP object has an instancemethod calledsendmail,whichwilltypicallybeusedtodotheworkofmailingamessage.Ittakesthreeparameters:
•Thesender-Astringwiththeaddressofthesender.
![Page 46: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/46.jpg)
•Thereceivers-Alistofstrings,oneforeachrecipient.
•Themessage-AmessageasastringformattedasspecifiedinthevariousRFCs.
Example:
Tosendane-mailusingPythonscript.
#!/usr/bin/python
importsmtplib
sender=‘[email protected]’
receivers=[‘[email protected]’]
message=“““From:FromPerson<[email protected]>
To:ToPerson<[email protected]>
Subject:SMTPe-mailtest
Thisisateste-mailmessage.
”””
try:
smtpObj=smtplib.SMTP(‘localhost’)
smtpObj.sendmail(sender,receivers,message)
print“Mailsentsuccessfully”
exceptSMTPException:
print“Errorinsendingmail”
Incase,ifyouarenotrunninganSMTPserveronyourlocalmachine,thenyoucanuse‘smtplib’ client to communicate with a remote SMTP server. Unless you’re using awebmailservice,youre-mailproviderwillhaveprovidedyouwithoutgoingmailserverdetailsthatyoucanprovidethem,asfollows:
smtplib.SMTP(‘mail.your-domain.com’,25)
SendinganHTMLE-mailsUsingPython:WhenyousendatextmessageusingPython,thenallthecontentwillbetreatedassimpletext.EvenifyouwillincludeHTMLtagsinatextmessage,itwillbedisplayedassimpletext and HTML tags will not be formatted according to HTML syntax. But PythonprovidesoptiontosendanHTMLmessageasactualHTMLmessage.Whilesendingane-mailmessage,youcanspecifyaMimeversion,contenttypeandcharactersettosendanHTMLe-mail.
![Page 47: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/47.jpg)
ExampletosendHTMLcontentasane-mail:
#!/usr/bin/python
importsmtplib
message=“““From:FromPerson<[email protected]>
To:ToPerson<[email protected]>
MIME-Version:1.0
Content-type:text/html
Subject:SMTPHTMLe-mailtest
Thisisane-mailmessagetobesentinHTMLformat
<b>HereisHTMLtextforyou.</b>
<h1>HereisHeadlineforyou.</h1>
”””
try:
smtpObj=smtplib.SMTP(‘localhost’)
smtpObj.sendmail(sender,receivers,message)
print“Mailsentsuccessfully”
exceptSMTPException:
print“Errorinsendingmail”
SendingAttachmentsasane-mail:To send an e-mail with mixed content requires setting Content-type header tomultipart/mixed.Then,textandattachmentsectionscanbespecifiedwithinboundaries.Aboundaryisstartedwithtwohyphensfollowedbyauniquenumber,whichcannotappearin themessage part of the e-mail. A final boundary denoting the e-mail’s final sectionmust also endwith two hyphens.Attached files should be encodedwith the pack(“m”)functiontohavebase64encodingbeforetransmission.
Exampletosendafile/tmp/test.txtasanattachment:
#!/usr/bin/python
importsmtplib
importbase64
filename=“/tmp/test.txt”
#Readafileandencodeitintobase64format
fo=open(filename,“rb”)
![Page 48: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/48.jpg)
filecontent=fo.read()
encodedcontent=base64.b64encode(filecontent)#base64
sender=‘[email protected]’
reciever=‘[email protected]’
marker=“TESTMARKER”
body=”””
Thisisatestemailtosendanattachement.
”””
#Definethemainheaders.
part1=“““From:FromPerson<[email protected]>
To:ToPerson<[email protected]>
Subject:SendingAttachement
MIME-Version:1.0
Content-Type:multipart/mixed;boundary=%s
—%s
”””%(marker,marker)
#Definethemessageaction
part2=“““Content-Type:text/plain
Content-Transfer-Encoding:8bit
%s
—%s
”””%(body,marker)
#Definetheattachmentsection
part3=“““Content-Type:multipart/mixed;name="%s"
Content-Transfer-Encoding:base64
Content-Disposition:attachment;filename=%s
%s
—%s—
”””%(filename,filename,encodedcontent,marker)
message=part1+part2+part3
try:
smtpObj=smtplib.SMTP(‘localhost’)
![Page 49: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/49.jpg)
smtpObj.sendmail(sender,reciever,message)
print“Mailsentsuccessfully”
exceptException:
print“Errorinsendingemail”
PYTHONMULTITHREADING
Inpythonyoucanrunmultiple threadsata time.Runningmultiple threads issimilar torunningseveraldifferentprogramswithfollowingbenefits:
•Multiplethreadswithinaprocesssharethesamedataspacewiththemainthreadandcanshareinformationorcommunicatewitheachothermoreeasilyascomparedtowhentheywereseparateprocesses.
•Threadssometimescalledlight-weightprocessesandtheydon’trequiremuchmemoryoverhead.A threadhasabeginning, anexecution sequence, andaconclusion. Ithasaninstructionpointerthatkeepstrackofwherewithinitscontextitiscurrentlyrunning.
•Itcanbepre-empted.
•Itcantemporarilybeputonholdwhileotherthreadsarerunning,thismethodiscalledyielding.
StartingaNewThread:Tostartanewthread,youneedtocallfollowingmethodavailableinthreadmodule:
thread.start_new_thread(function,args[,kwargs])
ThismethodisusedtoenableafastandefficientwaytocreatenewthreadsinbothLinuxandWindows.Themethodcall returns immediatelyand thechild threadstartsandcallsfunctionwiththepassedlistof‘agrs’.Whenfunctionreturns,thenthethreadterminates.Here, ‘args’ is a tuple of arguments; that uses an empty tuple to call function withoutpassinganyarguments.‘kwargs’isanoptionaldictionaryofkeywordarguments.
ForExample:
#!/usr/bin/python
importthread
importtime
![Page 50: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/50.jpg)
#Defineafunctionforthethread
defprint_time(threadName,delay):
count=0
whilecount<5:
time.sleep(delay)
count+=1
print“%s:%s”%(threadName,time.ctime(time.time()))
#Createtwothreadsasfollows
try:
thread.start_new_thread(print_time,(“MyThread-1”,2,))
thread.start_new_thread(print_time,(“MyThread-2”,4,))
except:
print“Errorinstartingathread”
while1:
pass
Output:
MyThread-1:WedJan01:4501:45:172015
MyThread-1:WedJan01:4501:45:192015
MyThread-2:WedJan01:4501:45:192015
MyThread-1:WedJan01:4501:45:212015
MyThread-2:WedJan01:4501:45:232015
MyThread-1:WedJan01:4501:45:232015
MyThread-1:WedJan01:4501:45:252015
MyThread-2:WedJan01:4501:45:272015
MyThread-2:WedJan01:4501:45:312015
MyThread-2:WedJan01:4501:45:352015
Althoughitisveryeffectiveforlow-levelthreading,butthethreadmoduleisverylimitedcomparedtothenewerthreadingmodule.
TheThreadingModule:
![Page 51: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/51.jpg)
NewthreadingmoduleinPython2.4providesmuchmorepowerful,high-levelsupportforthreads.Thethreadingmoduleexposesallthemethodsofthethreadmoduleandprovidessomeadditionalmethods:
•threading.activeCount():Returnsthenumberofthreadobjectsthatareactive.
• threading.currentThread(): Returns the number of thread objects in the caller’s threadcontrol.
•threading.enumerate():Returnsalistofallthreadobjectsthatarecurrentlyactive.
In addition to themethods, the threadingmodule has the Thread class that implementsthreading.ThemethodsprovidedbytheThreadclassaregivenbelow:
•run():Therun()methodistheentrypointforathread.
•start():Thestart()methodstartsathreadbycallingtherunmethod.
•join([time]):Thejoin()waitsforthreadstoterminate.
•isAlive():TheisAlive()methodcheckswhetherathreadisstillexecuting.
•getName():ThegetName()methodreturnsthenameofathread.
•setName():ThesetName()methodsetsthenameofathread.
CreatingThreadusingThreadingModule:Toimplementanewthreadusingthethreadingmodule,youmustfollowthepointsgivenbelow:
•DefineanewsubclassoftheThreadclass.
•Overridethe__init__(self[,args])methodtoaddadditionalarguments.
•Then,overridetherun(self[,args])methodtoimplementwhatthethreadshoulddowhenstarted.
OnceyouhavecreatedthenewThreadsubclass,youcancreateaninstanceofitandthenstartanewthreadbyinvokingthestart(),whichwillinturncallrun()method.
ForExample:
#!/usr/bin/python
importthreading
importtime
exitFlag=0
classmyBook(threading.Thread):
![Page 52: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/52.jpg)
def__init__(self,threadID,name,counter):
threading.Thread.__init__(self)
self.threadID=threadID
self.name=name
self.counter=counter
defrun(self):
print“Starting”+self.name
print_time(self.name,self.counter,5)
print“Exiting”+self.name
defprint_time(threadName,delay,counter):
whilecounter:
ifexitFlag:
thread.exit()
time.sleep(delay)
print“%s:%s”%(threadName,time.ctime(time.time()))
counter-=1
#Createnewthreads
thread1=myBook(1,“MyThread-1”,1)
thread2=myBook(2,“MyThread-2”,2)
#StartnewThreads
thread1.start()
thread2.start()
print“ExitFromMainThread”
Output:
StartingMyThread-1
StartingMyThread-2
ExitFromMainThread
MyThread-1:MonJul2701:45:10:032015
MyThread-1:MonJul2701:45:10:042015
MyThread-2:MonJul2701:45:10:042015
MyThread-1:MonJul2701:45:10:052015
![Page 53: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/53.jpg)
MyThread-1:MonJul2701:45:10:062015
MyThread-2:MonJul2701:45:10:062015
MyThread-1:MonJul2701:45:10:072015
ExitingMyThread-1
MyThread-2:MonJul2701:45:10:082015
MyThread-2:MonJul2701:45:10:102015
MyThread-2:MonJul2701:45:10:122015
ExitingMyThread-2
SynchronizingThreads:In python threading module includes a simple-to-implement locking mechanism whichwill allow you to synchronize the threads.A new lock is created by calling theLock()method, which returns the new lock. to force threads to run, The acquire(blocking)method of the new lock object is used. If blocking is set to 0, the thread will returnimmediatelywitha0value if the lockcannotbeacquiredandwitha1 if the lockwasacquired.Ifblockingissetto1,thethreadwillblockandwaitforthelocktobereleased.Therelease()methodofthethenewlockobjectwouldbeusedtoreleasethelockwhenitisnolongerrequired.
ForExample:
#!/usr/bin/python
importthreading
importtime
classmyBook(threading.Thread):
def__init__(self,threadID,name,counter):
threading.Thread.__init__(self)
self.threadID=threadID
self.name=name
self.counter=counter
defrun(self):
print“Starting”+self.name
#Getlocktosynchronizethreads
threadLock.acquire()
print_time(self.name,self.counter,3)
![Page 54: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/54.jpg)
#Freelocktoreleasenextthread
threadLock.release()
defprint_time(threadName,delay,counter):
whilecounter:
time.sleep(delay)
print“%s:%s”%(threadName,time.ctime(time.time()))
counter-=1
threadLock=threading.Lock()
threads=[]
#Createnewthreads
thread1=myBook(1,“MyThread-1”,1)
thread2=myBook(2,“MyThread-2”,2)
#StartnewThreads
thread1.start()
thread2.start()
#Addthreadstothreadlist
threads.append(thread1)
threads.append(thread2)
#Waitforallthreadstocomplete
fortinthreads:
t.join()
print“ExitingfromMainThread”
Output:
StartingMyThread-2
MyThread-1:MonJul2701:45:11:282015
MyThread-1:MonJul2701:45:11:292015
MyThread-1:MonJul2701:45:11:302015
MyThread-2:MonJul2701:45:11:322015
MyThread-2:MonJul2701:45:11:342015
MyThread-2:MonJul2701:45:11:362015
ExitingfromMainThread
![Page 55: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/55.jpg)
MultithreadedPriorityQueue:TheQueuemoduleinpythonallowsyoutocreateanewqueueobject,whichcanholdaspecificnumberofitems.MethodsthatareusedtocontroltheQueuearegivenbelow:
•get():Theget()removesandreturnsanitemfromthequeue.
•put():Theputaddsitemtoaqueue.
•qsize():Theqsize()returnsthenumberofitemsthatarecurrentlyinthequeue.
•empty():Theempty()returnsTrueifqueueisempty;otherwise,False.
•full():thefull()returnsTrueifqueueisfull;otherwise,False.
ForExample:
#!/usr/bin/python
importQueue
importthreading
importtime
exitFlag=0
classmyBook(threading.Thread):
def__init__(self,threadID,name,q):
threading.Thread.__init__(self)
self.threadID=threadID
self.name=name
self.q=q
defrun(self):
print“Starting”+self.name
process_data(self.name,self.q)
print“Exiting”+self.name
defprocess_data(threadName,q):
whilenotexitFlag:
queueLock.acquire()
![Page 56: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/56.jpg)
ifnotworkQueue.empty():
data=q.get()
queueLock.release()
print“%sprocessing%s”%(threadName,data)
else:
queueLock.release()
time.sleep(1)
threadList=[“MyThread-1”,“MyThread-2”,“Thread-3”]
nameList=[“A”,“B”,“C”,“D”,“E”]
queueLock=threading.Lock()
workQueue=Queue.Queue(10)
threads=[]
threadID=1
#Createnewthreads
fortNameinthreadList:
thread=myThread(threadID,tName,workQueue)
thread.start()
threads.append(thread)
threadID+=1
#Fillthequeue
queueLock.acquire()
forwordinnameList:
workQueue.put(word)
queueLock.release()
#Waitforqueuetoempty
whilenotworkQueue.empty():
pass
#Notifythreadsit’stimetoexit
exitFlag=1
#Waitforallthreadstocomplete
fortinthreads:
t.join()
![Page 57: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/57.jpg)
print“ExitingMainThread”
Output:
StartingThread-1
StartingThread-2
StartingThread-3
Thread-1processingA
Thread-2processingB
Thread-3processingC
Thread-1processingD
Thread-2processingE
ExitingThread-3
ExitingThread-1
ExitingThread-2
ExitingMainThread
PYTHONXMLPROCESSING
WhatisXML?XML is,ExtensibleMarkupLanguage (XML)and its likeHTMLorSGML.XML is aportable,opensourcelanguagethatallowstheprogrammerstodevelopapplicationsthatcan be read by other applications, regardless of operating system and/or developmentallanguage.XMLisextremelyusefulforkeepingtrackofsmalltomediumamountsofdata.
![Page 58: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/58.jpg)
XMLParserArchitecturesandAPIs:ThePythonstandardlibraryprovidesasetofinterfacestoworkwithXML.ThetwomostbasicandbroadlyusedAPIstoXMLdataaretheSAXandDOMinterfaces.
•SimpleAPI forXML (SAX):Here, you register callbacks for events of interest andthenlettheparserproceedthroughthedocument.Thisisusefulwhenyourdocumentsarelargeor youhavememory limitations, it parses the file as it reads it fromdisk and theentirefileisneverstoredinmemory.
• Document Object Model (DOM) API: This is a World Wide Web Consortiumrecommendationwhereintheentirefile isreadintomemoryandstoredinahierarchical(tree-based)formtorepresentallthefeaturesofanXMLdocument.
ThethingisthatSAXcan’tprocessinformationasfastasDOM,whenworkingwithlargefiles.Ontheotherhand,usingDOMcankillyourresources,especiallyifusedonalotofsmallfiles.SAXisread-only,whileDOMallowschangestotheXMLfile.AsthesetwoAPIs complement eachother, there is no reasonwhyyoucan’t use themboth for largeprojects.Let’sseeasimpleexampleforXMLfilemovies.xml:
<collectionshelf=“NewArrivals”>
<movietitle=“EnemyBehind”>
<type>War,Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>TalkaboutaUS-Japanwar</description>
</movie>
<movietitle=“Transformers”>
<type>Anime,ScienceFiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>8</stars>
<description>Aschientificfiction</description>
</movie>
<movietitle=“Trigun”>
<type>Anime,Action</type>
![Page 59: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/59.jpg)
<format>DVD</format>
<episodes>4</episodes>
<rating>PG</rating>
<stars>10</stars>
<description>VashtheStampede!</description>
</movie>
<movietitle=“Ishtar”>
<type>Comedy</type>
<format>VHS</format>
<rating>PG</rating>
<stars>2</stars>
<description>Viewableboredom</description>
</movie>
</collection>
ParsingXMLwithSAXAPIs:SAXisastandardinterfaceforevent-drivenXMLparsing.ForParsingXMLwithSAX,you need to create your own ContentHandler by subclassing xml.sax.ContentHandler.YourContentHandlerhandlestheparticulartagsandattributesofyourflavorofXML.AContentHandler object provides methods to handle various parsing events. Its owningparser calls ContentHandler methods as it passes the XML file. The methodsstartDocumentandendDocumentarecalledatthestartandtheendoftheXMLfile.TheContentHandleriscalledatthestartandendofeachelement.Herearesomemethodstounderstandbeforeproceeding:
Themake_parserMethod:Thismethodcreatesanewparserobjectandreturnsit.Theparserobjectcreatedwillbeofthefirstparsertypethesystemfinds.
xml.sax.make_parser([parser_list])
Hereparameter‘parser_list’,istheoptionalargumentconsistingofalistofparserstousewhichmustallimplementthemake_parsermethod.
TheparseMethod:ThismethodcreatesaSAXparserandusesittoparseadocument.
![Page 60: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/60.jpg)
xml.sax.parse(xmlfile,contenthandler[,errorhandler])
Here parameters ‘xmlfile’, is the name of theXML file to read from. ‘contenthandler’,mustbeaContentHandlerobject.and‘errorhandler’,mustbeaSAXErrorHandlerobject.
TheparseStringMethod:ThereisonemoremethodtocreateaSAXparserandtoparsethespecifiedXMLstring.
xml.sax.parseString(xmlstring,contenthandler[,errorhandler])
Here parameters ‘xmlstring’, is the name of the XML string to read from.‘contenthandler’, must be a ContentHandler object. ‘errorhandler’, must be a SAXErrorHandlerobject.
ForExample:
#!/usr/bin/python
importxml.sax
classMovieHandler(xml.sax.ContentHandler):
def__init__(self):
self.CurrentData=””
self.type=””
self.format=””
self.year=””
self.rating=””
self.stars=””
self.description=””
#Callwhenanelementstarts
defstartElement(self,tag,attributes):
self.CurrentData=tag
iftag==“movie”:
print“*****Movie*****”
title=attributes[“title”]
print“Title:”,title
#Callwhenanelementsends
![Page 61: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/61.jpg)
defendElement(self,tag):
ifself.CurrentData==“type”:
print“Type:”,self.type
elifself.CurrentData==“format”:
print“Format:”,self.format
elifself.CurrentData==“year”:
print“Year:”,self.year
elifself.CurrentData==“rating”:
print“Rating:”,self.rating
elifself.CurrentData==“stars”:
print“Stars:”,self.stars
elifself.CurrentData==“description”:
print“Description:”,self.description
self.CurrentData=””
#Callwhenacharacterisread
defcharacters(self,content):
ifself.CurrentData==“type”:
self.type=content
elifself.CurrentData==“format”:
self.format=content
elifself.CurrentData==“year”:
self.year=content
elifself.CurrentData==“rating”:
self.rating=content
elifself.CurrentData==“stars”:
self.stars=content
elifself.CurrentData==“description”:
self.description=content
if(__name__==“__main__”):
#createanXMLReader
parser=xml.sax.make_parser()
#turnoffnamepsaces
![Page 62: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/62.jpg)
parser.setFeature(xml.sax.handler.feature_namespaces,0)
#overridethedefaultContextHandler
Handler=MovieHandler()
parser.setContentHandler(Handler)
parser.parse(“movies.xml”)
Output:
*****Movie*****
Title:EnemyBehind
Type:War,Thriller
Format:DVD
Year:2003
Rating:PG
Stars:10
Description:TalkaboutaUS-Japanwar
*****Movie*****
Title:Transformers
Type:Anime,ScienceFiction
Format:DVD
Year:1989
Rating:R
Stars:8
Description:Aschientificfiction
*****Movie*****
Title:Trigun
Type:Anime,Action
Format:DVD
Rating:PG
Stars:10
Description:VashtheStampede!
*****Movie*****
Title:Ishtar
![Page 63: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/63.jpg)
Type:Comedy
Format:VHS
Rating:PG
Stars:2
Description:Viewableboredom
ParsingXMLwithDOMAPIs:The Document Object Model or “DOM,” is a cross-language API which is used foraccessingandmodifyingtheXMLdocuments.TheDOMisextremelyusefulforrandom-accessapplications.SAXallowstouseonedocumentatatime.IfyouarelookingatoneSAXelement,youhavenoaccesstoanotherone.theeasiestwaytoquicklyloadanXMLdocumentandtocreateaminidomobjectisbyusingthexml.dommodule.TheminidomobjectprovidesasimpleparsermethodthatwillquicklycreateaDOMtreefromtheXMLfile.
ForExample:
#!/usr/bin/python
fromxml.dom.minidomimportparse
importxml.dom.minidom
#OpenXMLdocumentusingminidomparser
DOMTree=xml.dom.minidom.parse(“movies.xml”)
collection=DOMTree.documentElement
ifcollection.hasAttribute(“shelf”):
print“Rootelement:%s”%collection.getAttribute(“shelf”)
#Getallthemoviesinthecollection
movies=collection.getElementsByTagName(“movie”)
#Printdetailofeachmovie.
formovieinmovies:
print“*****Movie*****”
ifmovie.hasAttribute(“title”):
print“Title:%s”%movie.getAttribute(“title”)
type=movie.getElementsByTagName(‘type’)[0]
print“Type:%s”%type.childNodes[0].data
format=movie.getElementsByTagName(‘format’)[0]
print“Format:%s”%format.childNodes[0].data
![Page 64: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/64.jpg)
rating=movie.getElementsByTagName(‘rating’)[0]
print“Rating:%s”%rating.childNodes[0].data
description=movie.getElementsByTagName(‘description’)[0]
print“Description:%s”%description.childNodes[0].data
Output:
Rootelement:NewArrivals
*****Movie*****
Title:EnemyBehind
Type:War,Thriller
Format:DVD
Rating:PG
Description:TalkaboutaUS-Japanwar
*****Movie*****
Title:Transformers
Type:Anime,ScienceFiction
Format:DVD
Rating:R
Description:Aschientificfiction
*****Movie*****
Title:Trigun
Type:Anime,Action
Format:DVD
Rating:PG
Description:VashtheStampede!
*****Movie*****
Title:Ishtar
Type:Comedy
Format:VHS
Rating:PG
Description:Viewableboredom
PYTHONPROGRAMS
![Page 65: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/65.jpg)
PythonProgramtoAddTwoMatrices
#Programtoaddtwomatrices
#usingnestedloop
X=[[12,7,3],
[4,5,6],
[7,8,9]]
Y=[[5,8,1],
[6,7,3],
[4,5,9]]
result=[[0,0,0],
[0,0,0],
[0,0,0]]
#iteratethroughrows
foriinrange(len(X)):
#iteratethroughcolumns
forjinrange(len(X[0])):
result[i][j]=X[i][j]+Y[i][j]
forrinresult:
print(r)
Output:
[17,15,4]
[10,12,9]
[11,13,18]
PythonProgramtoAddTwoNumbers
#Thisprogramaddstwonumbers
#Numbersareprovidedbytheuser
![Page 66: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/66.jpg)
#Storeinputnumbers
num1=input(‘Enterfirstnumber:‘)
num2=input(‘Entersecondnumber:‘)
#Addtwonumbers
sum=float(num1)+float(num2)
#Displaythesum
print(‘Thesumof{0}and{1}is{2}’.format(num1,num2,sum))
Output:
Enterfirstnumber:5.3
Entersecondnumber:3.3
Thesumof5.3and3.3is8.6
PythonProgramtoCalculatetheAreaofaTriangle
#PythonProgramtofindtheareaoftriangle
#Threesidesofthetriangle
#a,b,careprovidedbytheuser
a=float(input(‘Enterfirstside:‘))
b=float(input(‘Entersecondside:‘))
c=float(input(‘Enterthirdside:‘))
#calculatethesemi-perimeter
s=(a+b+c)/2
#calculatethearea
area=(s*(s-a)*(s-b)*(s-c))**0.5
print(‘Theareaofthetriangleis%0.2f’%area)
Output:
Enterfirstside:5
Entersecondside:6
Enterthirdside:7
![Page 67: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/67.jpg)
Theareaofthetriangleis14.70
PythonProgramtoCheckArmstrongNumber
#Pythonprogramtoifthe
#numberprovidedbythe
#userisanArmstrongnumber
#ornot
#takeinputfromtheuser
num=int(input(“Enteranumber:“))
#initialisesum
sum=0
#findthesumofthecubeofeachdigit
temp=num
whiletemp>0:
digit=temp%10
sum+=digit**3
temp//=10
#displaytheresult
ifnum==sum:
print(num,“isanArmstrongnumber”)
else:
print(num,“isnotanArmstrongnumber”)
Output1
Enteranumber:663
663isnotanArmstrongnumber
Output2
![Page 68: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/68.jpg)
Enteranumber:371
407isanArmstrongnumber
PythonProgramtoCheckifaNumberisOddorEven
#Pythonprogramtocheckif
#theinputnumberisoddoreven.
#Anumberisevenifdivision
#by2givearemainderof0.
#Ifremainderis1,itisodd.
num=int(input(“Enteranumber:“))
if(num%2)==0:
print(“{0}isEven”.format(num))
else:
print(“{0}isOdd”.format(num))
Output1
Enteranumber:73
73isOdd
Output2
Enteranumber:24
24isEven
PythonProgramtoCheckifaNumberisPositive,NegativeorZero
#Inthispythonprogram,weinputanumber
#checkifthenumberispositiveor
#negativeorzeroanddisplay
#anappropriatemessage
num=float(input(“Enteranumber:“))
![Page 69: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/69.jpg)
ifnum>0:
print(“Positivenumber”)
elifnum==0:
print(“Zero”)
else:
print(“Negativenumber”)
#Inthisprogram,weinputanumber
#checkifthenumberispositiveor
#negativeorzeroanddisplay
#anappropriatemessage
#Thistimeweusenestedif
num=float(input(“Enteranumber:“))
ifnum>=0:
ifnum==0:
print(“Zero”)
else:
print(“Positivenumber”)
else:
print(“Negativenumber”)
Output1
Enteranumber:5
Positivenumber
Output2
Enteranumber:0
Zero
Output3
Enteranumber:-4
Negativenumber
![Page 70: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/70.jpg)
PythonProgramtoCheckifaStringisPalindromeorNot
#Programtocheckifastring
#ispalindromeornot
#takeinputfromtheuser
my_str=input(“Enterastring:“)
#makeitsuitableforcaselesscomparison
my_str=my_str.casefold()
#reversethestring
rev_str=reversed(my_str)
#checkifthestringisequaltoitsreverse
iflist(my_str)==list(rev_str):
print(“Itispalindrome”)
else:
print(“Itisnotpalindrome”)
Output1
Enterastring:aIbohPhoBiA
Itispalindrome
Output2
Enterastring:13344331
Itispalindrome
Output3
Enterastring:palindrome
Itisnotpalindrome
PythonProgramtoCheckLeapYear
#Pythonprogramtocheckif
![Page 71: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/71.jpg)
#theinputyearis
#aleapyearornot
year=int(input(“Enterayear:“))
if(year%4)==0:
if(year%100)==0:
if(year%400)==0:
print(“{0}isaleapyear”.format(year))
else:
print(“{0}isnotaleapyear”.format(year))
else:
print(“{0}isaleapyear”.format(year))
else:
print(“{0}isnotaleapyear”.format(year))
Output1
Enterayear:2012
2012isaleapyear
Output2
Enterayear:2015
2015isnotaleapyear
PythonProgramtoCheckPrimeNumber
#Pythonprogramtocheckif
#theinputnumberis
#primeornot
#takeinputfromtheuser
num=int(input(“Enteranumber:“))
#primenumbersaregreaterthan1
ifnum>1:
#checkforfactors
![Page 72: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/72.jpg)
foriinrange(2,num):
if(num%i)==0:
print(num,“isnotaprimenumber”)
print(i,“times”,num//i,“is”,num)
break
else:
print(num,“isaprimenumber”)
#ifinputnumberislessthan
#orequalto1,itisnotprime
else:
print(num,“isnotaprimenumber”)
Output1
Enteranumber:407
407isnotaprimenumber
11times37is407
Output2
Enteranumber:853
853isaprimenumber
PythonProgramtoConvertCelsiusToFahrenheit
#PythonProgramtoconverttemperaturein
#celsiustofahrenheitwhere,inputis
#providedbytheuserin
#degreecelsius
#takeinputfromtheuser
celsius=float(input(‘EnterdegreeCelsius:‘))
#calculatefahrenheit
fahrenheit=(celsius*1.8)+32
print(‘%0.1fdegreeCelsiusisequalto%0.1fdegreeFahrenheit’%(celsius,fahrenheit))
Output
![Page 73: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/73.jpg)
EnterdegreeCelsius:43.7
43.7degreeCelsiusisequalto110.66degreeFahrenheit
PythonProgramtoConvertDecimalintoBinary,OctalandHexadecimal
#Pythonprogramtoconvertdecimal
#numberintobinary,octaland
#hexadecimalnumbersystem
#Takedecimalnumberfromuser
dec=int(input(“Enteraninteger:“))
print(“Thedecimalvalueof”,dec,“is:”)
print(bin(dec),“inbinary.”)
print(oct(dec),“inoctal.”)
print(hex(dec),“inhexadecimal.”)
Output
Enteraninteger:133
Thedecimalvalueof133is:
0b10000101inbinary.
0o205inoctal.
0x85inhexadecimal.
PythonProgramtoConvertDecimaltoBinaryUsingRecursion
#Pythonprogramtoconvertdecimal
#numberintobinarynumber
#usingrecursivefunction
![Page 74: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/74.jpg)
defbinary(n):
“““Functiontoprintbinarynumber
fortheinputdecimalusingrecursion”””
ifn>1:
binary(n//2)
print(n%2,end=”)
#Takedecimalnumberfromuser
dec=int(input(“Enteraninteger:“))
binary(dec)
Output
Enteraninteger:76
1001100
PythonProgramtoConvertKilometerstoMiles
#Programtoconvertkilometers
#intomileswhere,inputis
#providedbytheuserin
#kilometers
#takeinputfromtheuser
kilometers=float(input(‘Howmanykilometers?:‘))
#conversionfactor
conv_fac=0.621371
#calculatemiles
miles=kilometers*conv_fac
print(‘%0.3fkilometersisequalto%0.3fmiles’%(kilometers,miles))
Output
Howmanykilometers?:3.7
5.500kilometersisequalto2.300miles
![Page 75: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/75.jpg)
PythonProgramtoCounttheNumberofEachVowel
#Programtocountthenumberof
#eachvowelinastring
#stringofvowels
vowels=‘aeiou’
#takeinputfromtheuser
ip_str=input(“Enterastring:“)
#makeitsuitableforcaselesscomparisions
ip_str=ip_str.casefold()
#makeadictionarywitheachvowelakeyandvalue0
count={}.fromkeys(vowels,0)
#countthevowels
forcharinip_str:
ifcharincount:
count[char]+=1
print(count)
Output
Enterastring:Iwelcomeyoualltoreadmybookandlearnpythoneasily.
{‘e’:4,‘u’:1,‘o’:6,‘a’:5,‘i’:1}
PythonProgramtoDisplayCalendar
#Pythonprogramtodisplaycalendar
#ofgivenmonthoftheyear
![Page 76: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/76.jpg)
#importmodule
importcalendar
#askofmonthandyear
yy=int(input(“Enteryear:“))
mm=int(input(“Entermonth:“))
#displaythecalendar
print(calendar.month(yy,mm))
Output
Enteryear:2015
Entermonth:09
September2015
Mo
Tu
We
Th
Fr
Sa
Su
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
PythonProgramtoDisplayFibonacciSequenceUsingRecursion
#PythonprogramtodisplaytheFibonacci
#sequenceupton-thtermusing
#recursivefunctions
defrecur_fibo(n):
![Page 77: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/77.jpg)
“““Recursivefunctionto
printFibonaccisequence”””
ifn<=1:
returnn
else:
return(recur_fibo(n-1)+recur_fibo(n-2))
#takeinputfromtheuser
nterms=int(input(“Howmanyterms?“))
#checkifthenumberoftermsisvalid
ifnterms<=0:
print(“Pleseenterapositiveinteger”)
else:
print(“Fibonaccisequence:”)
foriinrange(nterms):
print(recur_fibo(i))
Output
Howmanyterms?8
Fibonaccisequence:
0
1
1
2
3
5
8
13
PythonProgramToDisplayPowersof2UsingAnonymousFunction
#PythonProgramtodisplay
![Page 78: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/78.jpg)
#thepowersof2using
#anonymousfunction
#Takenumberoftermsfromuser
terms=int(input(“Howmanyterms?“))
#useanonymousfunction
result=list(map(lambdax:2**x,range(terms)))
#displaytheresult
foriinrange(terms):
print(“2raisedtopower”,i,“is”,result[i])
Output
Howmanyterms?6
2raisedtopower0is1
2raisedtopower1is2
2raisedtopower2is4
2raisedtopower3is8
2raisedtopower4is16
2raisedtopower5is32
PythonProgramtoDisplaythemultiplicationTable
#Pythonprogramtofindthemultiplication
#table(from1to10)c
#ofanumberinputbytheuser
#takeinputfromtheuser
num=int(input(“Displaymultiplicationtableof?“))
#useforlooptoiterate10times
foriinrange(1,11):
print(num,‘x’,i,’=’,num*i)
![Page 79: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/79.jpg)
Output
Displaymultiplicationtableof?7
7x1=7
7x2=14
7x3=21
7x4=28
7x5=35
7x6=42
7x7=49
7x8=56
7x9=63
7x10=70
PythonProgramtoFindArmstrongNumberinanInterval
#Programtoasktheuser
#forarangeanddisplay
#allArmstrongnumbersin
#thatinterval
#takeinputfromtheuser
lower=int(input(“Enterlowerrange:“))
upper=int(input(“Enterupperrange:“))
fornuminrange(lower,upper+1):
#initializesum
sum=0
#findthesumofthecubeofeachdigit
temp=num
whiletemp>0:
digit=temp%10
![Page 80: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/80.jpg)
sum+=digit**3
temp//=10
ifnum==sum:
print(num)
Output
Enterlowerrange:0
Enterupperrange:999
0
1
153
370
371
407
PythonProgramtoFindASCIIValueofCharacter
#Programtofindthe
#ASCIIvalueofthe
#givencharacter
#Takecharacterfromuser
c=input(“Enteracharacter:“)
print(“TheASCIIvalueof’”+c+”’is”,ord(c))
Output1
Enteracharacter:k
TheASCIIvalueof‘k’is107
Output2
Enteracharacter:=
TheASCIIvalueof‘=’is61
PythonProgramtoFindFactorialofNumberUsingRecursion
#Pythonprogramtofindthe
![Page 81: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/81.jpg)
#factorialofanumber
#usingrecursion
defrecur_factorial(n):
“““Functiontoreturnthefactorial
ofanumberusingrecursion”””
ifn==1:
returnn
else:
returnn*recur_factorial(n-1)
#takeinputfromtheuser
num=int(input(“Enteranumber:“))
#checkisthenumberisnegative
ifnum<0:
print(“Sorry,factorialdoesnotexistfornegativenumbers”)
elifnum==0:
print(“Thefactorialof0is1”)
else:
print(“Thefactorialof”,num,“is”,recur_factorial(num))
Output1
Enteranumber:-5
Sorry,factorialdoesnotexistfornegativenumbers
Output2
Enteranumber:5
Thefactorialof5is120
PythonProgramtoFindFactorsofNumber
#PythonProgramtofindthe
#factorsofanumber
#defineafunction
defprint_factors(x):
“““Thisfunctiontakesa
![Page 82: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/82.jpg)
numberandprintsthefactors”””
print(“Thefactorsof”,x,“are:”)
foriinrange(1,x+1):
ifx%i==0:
print(i)
#takeinputfromtheuser
num=int(input(“Enteranumber:“))
print_factors(num)
Output
Enteranumber:120
Thefactorsof120are:
1
2
3
4
5
6
8
10
12
15
20
24
30
40
60
120
PythonProgramtoFindHashofFile
![Page 83: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/83.jpg)
#PythonrogramtofindtheSHA-1
#messagedigestofafile
#importhashlibmodule
importhashlib
defhash_file(filename):
””““ThisfunctionreturnstheSHA-1hash
ofthefilepassedintoit”””
#makeahashobject
h=hashlib.sha1()
#openfileforreadinginbinarymode
withopen(filename,‘rb’)asfile:
#looptilltheendofthefile
chunk=0
whilechunk!=b”:
#readonly1024bytesatatime
chunk=file.read(1024)
h.update(chunk)
#returnthehexrepresentationofdigest
returnh.hexdigest()
message=hash_file(“track1.mp3”)
print(message)
Output
633d7356947eec543c50b76a1852f92427f4dca9
PythonProgramtoFindHCForGCD
#Pythonprogramtofindthe
#H.C.Foftwoinputnumber
#defineafunction
defhcf(x,y):
![Page 84: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/84.jpg)
“““Thisfunctiontakestwo
integersandreturnstheH.C.F”””
#choosethesmallernumber
ifx>y:
smaller=y
else:
smaller=x
foriinrange(1,smaller+1):
if((x%i==0)and(y%i==0)):
hcf=i
return
#takeinputfromtheuser
num1=int(input(“Enterfirstnumber:“))
num2=int(input(“Entersecondnumber:“))
print(“TheH.C.F.of”,num1,“and”,num2,“is”,hcf(num1,num2))
Output
Enterfirstnumber:40
Entersecondnumber:48
TheH.C.F.of40and48is8
PythonProgramtoFindLCM
#PythonProgramtofindthe
#L.C.M.oftwoinputnumber
#defineafunction
deflcm(x,y):
“““Thisfunctiontakestwo
integersandreturnstheL.C.M.”””
#choosethegreaternumber
![Page 85: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/85.jpg)
ifx>y:
greater=x
else:
greater=y
while(True):
if((greater%x==0)and(greater%y==0)):
lcm=greater
break
greater+=1
returnlcm
#takeinputfromtheuser
num1=int(input(“Enterfirstnumber:“))
num2=int(input(“Entersecondnumber:“))
print(“TheL.C.M.of”,num1,“and”,num2,“is”,lcm(num1,num2))
Output
Enterfirstnumber:3
Entersecondnumber:4
TheL.C.M.of3and4is12
PythonProgramtoFindNumbersDivisiblebyAnotherNumber
#PythonProgramtofindnumbers
#divisiblebythirteen
#fromalistusinganonymousfunction
#Takealistofnumbers
my_list=[12,65,54,39,102,339,221,]
#useanonymousfunctiontofilter
result=list(filter(lambdax:(x%13==0),my_list))
#displaytheresult
print(“Numbersdivisibleby13are”,result)
![Page 86: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/86.jpg)
Output
Numbersdivisibleby13are[65,39,221]
PythonProgramtoFindSumofNaturalNumbersUsingRecursion
#Pythonprogramtofindthesumof
#naturalnumbersupton
#usingrecursivefunction
defrecur_sum(n):
“““Functiontoreturnthesum
ofnaturalnumbersusingrecursion”””
ifn<=1:
returnn
else:
returnn+recur_sum(n-1)
#takeinputfromtheuser
num=int(input(“Enteranumber:“))
ifnum<0:
print(“Enterapositivenumber”)
else:
print(“Thesumis”,recur_sum(num))
Output
Enteranumber:10
Thesumis55
PythonProgramtoFindtheFactorialofaNumber
#Pythonprogramtofindthe
#factorialofanumber
#providedbytheuser
#takeinputfromtheuser
num=int(input(“Enteranumber:“))
![Page 87: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/87.jpg)
factorial=1
#checkifthenumberisnegative,positiveorzero
ifnum<0:
print(“Sorry,factorialdoesnotexistfornegativenumbers”)
elifnum==0:
print(“Thefactorialof0is1”)
else:
foriinrange(1,num+1):
factorial=factorial*i
print(“Thefactorialof”,num,“is”,factorial)
Output1
Enteranumber:-18
Sorry,factorialdoesnotexistfornegativenumbers
Output2
Enteranumber:9
Thefactorialof9is362,880
PythonProgramtoFindtheLargestAmongThreeNumbers
#Pythonprogramtofindthelargest
#numberamongthethree
#inputnumbers
#takethreenumbersfromuser
num1=float(input(“Enterfirstnumber:“))
num2=float(input(“Entersecondnumber:“))
num3=float(input(“Enterthirdnumber:“))
if(num1>num2)and(num1>num3):
largest=num1
elif(num2>num1)and(num2>num3):
largest=num2
![Page 88: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/88.jpg)
else:
largest=num3
print(“Thelargestnumberis”,largest)
Output1
Enterfirstnumber:8
Entersecondnumber:16
Enterthirdnumber:4
Thelargestnumberis16.0
Output2
Enterfirstnumber:-6
Entersecondnumber:-15
Enterthirdnumber:0
Thelargestnumberis0.0
PythonProgramtoFindtheSize(Resolution)ofImage
#PythonProgramtofindtheresolution
#ofajpegimagewithoutusing
#anyexternallibraries
defjpeg_res(filename):
””““Thisfunctionprintstheresolution
ofthejpegimagefilepassedintoit”””
#openimageforreadinginbinarymode
withopen(filename,‘rb’)asimg_file:
#heightofimage(in2bytes)isat164thposition
img_file.seek(163)
#readthe2bytes
a=img_file.read(2)
#calculateheight
height=(a[0]<<8)+a[1]
#next2bytesiswidth
![Page 89: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/89.jpg)
a=img_file.read(2)
#calculatewidth
width=(a[0]<<8)+a[1]
print(“Theresolutionoftheimageis”,width,“x”,height)
jpeg_res(“image.jpg”)
Output
Theresolutionoftheimageis180x200
PythonProgramtoFindtheSquareRoot
#PythonProgramtocalculatethesquareroot
num=float(input(‘Enteranumber:‘))
num_sqrt=num**0.5
print(‘Thesquarerootof%0.3fis%0.3f’%(num,num_sqrt))
Output
Enteranumber:11
Thesquarerootof11.000is3.316
PythonProgramtoFindtheSumofNaturalNumbers
#Pythonprogramtofindthesumof
#naturalnumbersupton
#wherenisprovidedbyuser
#takeinputfromtheuser
num=int(input(“Enteranumber:“))
ifnum<0:
print(“Enterapositivenumber”)
else:
![Page 90: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/90.jpg)
sum=0
#usewhilelooptoiterateuntillzero
while(num>0):
sum+=num
num-=1
print(“Thesumis”,sum)
Output
Enteranumber:10
Thesumis55
PythonProgramtoGenerateaRandomNumber
#Programtogeneratearandomnumber
#between0and9
#importtherandommodule
importrandom
print(random.randint(0,9))
Output
5
PythonProgramtoIllustrateDifferentSetOperations
#Programtoperformdifferent
#setoperationslikeinmathematics
#definethreesets
E={0,2,4,6,8};
N={1,2,3,4,5};
#setunion
print(“UnionofEandNis”,E|N)
#setintersection
![Page 91: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/91.jpg)
print(“IntersectionofEandNis”,E&N)
#setdifference
print(“DifferenceofEandNis”,E-N)
#setsymmetricdifference
print(“SymmetricdifferenceofEandNis”,E^N)
Output
UnionofEandNis{0,1,2,3,4,5,6,8}
IntersectionofEandNis{2,4}
DifferenceofEandNis{8,0,6}
SymmetricdifferenceofEandNis{0,1,3,5,6,8}
PythonProgramtoMakeaSimpleCalculator
#Programmakeasimplecalculator
#thatcanadd,subtract,multiply
#anddivideusingfunctions
#definefunctions
defadd(x,y):
“““Thisfunctionaddstwonumbers”””
returnx+y
defsubtract(x,y):
“““Thisfunctionsubtractstwonumbers”””
returnx-y
defmultiply(x,y):
“““Thisfunctionmultipliestwonumbers”””
returnx*y
defdivide(x,y):
“““Thisfunctiondividestwonumbers”””
returnx/y
#takeinputfromtheuser
![Page 92: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/92.jpg)
print(“Selectoperation.”)
print(“1.Add”)
print(“2.Subtract”)
print(“3.Multiply”)
print(“4.Divide”)
choice=input(“Enterchoice(1/2/3/4):”)
num1=int(input(“Enterfirstnumber:“))
num2=int(input(“Entersecondnumber:“))
ifchoice==‘1’:
print(num1,”+”,num2,”=”,add(num1,num2))
elifchoice==‘2’:
print(num1,”-“,num2,”=”,subtract(num1,num2))
elifchoice==‘3’:
print(num1,”*”,num2,”=”,multiply(num1,num2))
elifchoice==‘4’:
print(num1,”/”,num2,”=”,divide(num1,num2))
else:
print(“Invalidinput”)
Output
Selectoperation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enterchoice(1/2/3/4):2
Enterfirstnumber:20
Entersecondnumber:11
20-11=9
![Page 93: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/93.jpg)
PythonProgramtoMultiplyTwoMatrices
#Programtomultiplytwomatrices
#usingnestedloops
#3x3matrix
X=[[12,7,3],
[4,5,6],
[7,8,9]]
#3x4matrix
Y=[[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
#resultis3x4
result=[[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
#iteratethroughrowsofX
foriinrange(len(X)):
#iteratethroughcolumnsofY
forjinrange(len(Y[0])):
#iteratethroughrowsofY
forkinrange(len(Y)):
result[i][j]+=X[i][k]*Y[k][j]
forrinresult:
print(r)
Output
![Page 94: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/94.jpg)
[114,160,60,27]
[74,97,73,14]
[119,157,112,23]
PythonProgramtoPrintallPrimeNumbersinanInterval
#Pythonprogramtoasktheuser
#forarangeanddisplay
#alltheprimenumbersin
#thatinterval
#takeinputfromtheuser
lower=int(input(“Enterlowerrange:“))
upper=int(input(“Enterupperrange:“))
fornuminrange(lower,upper+1):
#primenumbersaregreaterthan1
ifnum>1:
foriinrange(2,num):
if(num%i)==0:
break
else:
print(num)
Output
Enterlowerrange:100
Enterupperrange:200
101
103
107
109
113
127
![Page 95: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/95.jpg)
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
PythonProgramtoPrintHiGoodMorning!
#ThisprogramprintsHi,GoodMorning!
print(‘Hi,GoodMorning!’)
Output
Hi,GoodMorning!
PythonprogramtoPrinttheFibonaccisequence
#Programtodisplaythefibonacci
#sequenceupton-thternwhere
#nisprovidedbytheuser
#takeinputfromtheuser
nterms=int(input(“Howmanyterms?“))
![Page 96: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/96.jpg)
#firsttwoterms
n1=0
n2=1
count=2
#checkifthenumberoftermsisvalid
ifnterms<=0:
print(“Pleseenterapositiveinteger”)
elifnterms==1:
print(“Fibonaccisequence:”)
print(n1)
else:
print(“Fibonaccisequence:”)
print(n1,”,”,n2,end=’,‘)
whilecount<nterms:
nth=n1+n2
print(nth,end=’,‘)
#updatevalues
n1=n2
n2=nth
count+=1
Output
Howmanyterms?12
Fibonaccisequence:
0,1,1,2,3,5,8,13,21,34,55,89
PythonProgramtoRemovePunctuationsformaString
#Programtoallpunctuationsfromthe
#stringprovidedbytheuser
![Page 97: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/97.jpg)
#definepunctuations
punctuations=”’!()-[]{};:’”\,<>./?@#$%^&*_~”’
#takeinputfromtheuser
my_str=input(“Enterastring:“)
#removepunctuationsfromthestring
no_punct=””
forcharinmy_str:
ifcharnotinpunctuations:
no_punct=no_punct+char
#displaytheunpunctuatedstring
print(no_punct)
Output
Enterastring:“Hello!!!”,GoodMorning–Haveagoodday.
HelloGoodMorningHaveagoodday
PythonProgramtoShuffleDeckofCards
#Pythonprogramtoshufflea
#deckofcardusingthe
#modulerandomanddraw5cards
#importmodules
importitertools,random
#makeadeckofcards
deck=list(itertools.product(range(1,14),[‘Spade’,‘Heart’,‘Diamond’,‘Club’]))
#shufflethecards
random.shuffle(deck)
#drawfivecards
print(“Yougot:”)
foriinrange(5):
print(deck[i][0],“of”,deck[i][1])
![Page 98: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/98.jpg)
Output1
Yougot:
5ofHeart
1ofHeart
8ofSpade
12ofSpade
4ofSpade
Output2
Yougot:
10ofClub
1ofHeart
3ofDiamond
2ofClub
3ofClub
PythonProgramtoSolveQuadraticEquation
#Solvethequadraticequation
#ax**2+bx+c=0
#a,b,careproviedbytheuser
#importcomplexmathmodule
importcmath
a=float(input(‘Entera:‘))
b=float(input(‘Enterb:‘))
c=float(input(‘Enterc:‘))
#calculatethediscriminant
d=(b**2)-(4*a*c)
#findtwosolutions
sol1=(-b-cmath.sqrt(d))/(2*a)
![Page 99: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/99.jpg)
sol2=(-b+cmath.sqrt(d))/(2*a)
print(‘Thesolutionare{0}and{1}’.format(sol1,sol2))
Output
Entera:1
Enterb:5
Enterc:6
Thesolutionsare(-3+0j)and(-2+0j)
PythonProgramtoSortWordsinAlphabeticOrder
#Programtosortalphabeticallythewords
#formastringprovidedbytheuser
#takeinputfromtheuser
my_str=input(“Enterastring:“)
#breakdownthestringintoalistofwords
words=my_str.split()
#sortthelist
words.sort()
#displaythesortedwords
forwordinwords:
print(word)
Output
Enterastring:thisismysecondpythonbooktoread
book
is
my
python
read
second
this
![Page 100: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/100.jpg)
to
PythonProgramtoSwapTwoVariables
#Pythonprogramtoswaptwovariables
#providedbytheuser
x=input(‘Entervalueofx:‘)
y=input(‘Entervalueofy:‘)
#createatemporaryvariable
#andswapthevalues
temp=x
x=y
y=temp
print(‘Thevalueofxafterswapping:{}’.format(x))
print(‘Thevalueofyafterswapping:{}’.format(y))
Output
Entervalueofx:8
Entervalueofy:15
Thevalueofxafterswapping:15
Thevalueofyafterswapping:8
PythonProgramtoTransposeaMatrix
#Programtotransposeamatrix
#usingnestedloop
X=[[12,7],
[4,5],
[3,8]]
![Page 101: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/101.jpg)
result=[[0,0,0],
[0,0,0]]
#iteratethroughrows
foriinrange(len(X)):
#iteratethroughcolumns
forjinrange(len(X[0])):
result[j][i]=X[i][j]
forrinresult:
print(r)
Output
[12,4,3]
[7,5,8]
NOTE
This isallaboutPythonProgramming.These thingsaremust tounderstandifyouareabeginnerinlearningPythonProgramLanguage.IHopeyoulikedthebookandlearnedalotfromit.Ihavealsosharedbasicpythonprogramsinthisbook,sowhatareyouwaitingfor??TurnonyoursystemandstartcreatingyourPythonPrograms.
MOREFROMAUTHOR
![Page 102: Complete Guide For Python Programming · Complete Guide For Python Programming Quick & Easy Guide To Learn Python By: James P. Long ACKNOWLEDGMENTS For my students and friends, who](https://reader030.fdocuments.in/reader030/viewer/2022040115/5e7aa8303399e747ea16b616/html5/thumbnails/102.jpg)
PythonProgrammingForBeginners:QuickAndEasyGuideForPythonProgrammers
©Copyright2014–JamesP.Long
Allrightsreserved.Withoutlimitingtherightsundercopyrightreservedabove,nopartofthis publication maybe reproduced, stored in or introduced into a retrieval system, ortransmitted in any form, or by any means (electronic, mechanical, photocopying,recordingorotherwise)withoutthepriorwrittenpermissionofboththecopyrightownerandthepublisherofthisbook.
Theauthorandpublishersofthisbookdonotdispensemedicaladvicenorprescribetotheuseofany techniqueor treatmentforhealthdisordersandanysortofmedicalproblemswithouttheadviceofamedicalprofessional,eitherdirectlyorindirectly.Itistheintentionofthisbooktoonlyofferinformationofageneralnature.Anyspecificproblemsshouldbereferredtoyourdoctor.Ifyouchoosetousethisinformationforyourselfthentheauthorandpublisherassumenoresponsibilitywhatsoever.