Tải bản đầy đủ (.pdf) (161 trang)

Python practical python programming for beginners and experts

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (11.15 MB, 161 trang )


PythonProgramming


PracticalPythonProgrammingFor
BeginnersandExperts
JonathanYates



TextCopyright©JonathanYates
Allrightsreserved.Nopartofthisguidemaybereproducedinanyformwithout
permissioninwritingfromthepublisherexceptinthecaseofbriefquotationsembodied
incriticalarticlesorreviews.
Legal&Disclaimer
Thisdocumentisgearedtowardsprovidingexactandreliableinformationinregardstothe
topic and issues covered. The publication is sold on the idea that the publisher is not
requiredtorenderanaccounting,officiallypermitted,orotherwise,qualifiedservices.If
adviceisnecessary,legalorprofessional,apracticedindividualintheprofessionshould
beordered.

- From a Declaration of Principles which was accepted and approved equally by a
Committee of the American Bar Association and a Committee of Publishers and
Associations.

In no way is it legal to reproduce, duplicate, or transmit any part of this document by
either electronic means or printed format. Recording of this publication is strictly
prohibited,andanystorageofthisdocumentisnotallowedunlesswithwrittenpermission
fromthepublisher.Allrightsreserved.

Theinformationprovidedhereinisstatedtobetruthfulandconsistent,inthatanyliability,


regarding inattention or otherwise, by any usage or abuse of any policies, processes, or
directionscontainedwithinisthesolitaryandutterresponsibilityoftherecipientreader.
Under no circumstances will any legal responsibility or blame be held against the
publisher for any reparation, damages, or monetary loss due to the information herein,
eitherdirectlyorindirectly.

Respectiveauthorsownallcopyrightsnotheldbythepublisher.

Theinformationhereinisofferedforinformationalpurposessolelyandisuniversalasso.
The presentation of the information is without a contract or any type of guarantee
assurance.



Thetrademarksthatareusedarewithoutanyconsent,andthepublicationofthetrademark
is without permission or backing by the trademark owner. All trademarks and brands
within this book are for clarifying purposes only and are the owned by the owners
themselves,notaffiliatedwiththisdocument.


TableofContents
Introduction
Chapter1:AnIntroductiontoPython
Chapter2:InstallingPythonandSettinguptheEnvironment
Chapter3:CommonPythonSyntax
Chapter4:TypesofVariablesinPython
Chapter5:UsingOperatorsandOperands
Chapter6:UsingSequentialLoops
Chapter7:DecisionMakingandExpressions
Chapter8:StringsandFunctionsinPython

Chapter9:Creating,Using,andModifyingLists
Chapter10:TuplesandDataTypes
Chapter11:DictionaryOperationandFunctions
Chapter12:MasteringDateandTime
Chapter13:UserDefinedFunctions
Chapter14:OrganizingCodewithModules
Chapter15:I/OInputUsedinPython
Chapter16:ExceptionsandAssertions
Chapter17:ObjectOrientedProgramming
Chapter18:PythonRegularExpressions.
Chapter19:PythonMultithreadedProgramming
Chapter20:Conclusion



Chapter1
AnIntroductiontoPython


Are you aware that websites like YouTube and Dropbox make use of Python
Programmingintheirsourcecode?Pythonisacommonlyusedlanguagewhichonecan
easilyunderstandandapply.YoucanmakenearlyanythingusingPython.Mostsystems
today (Mac, Linux, UNIX, etc.) have Python installed as a default setting since it is an
opensourceandfreelanguage.Uponreadingthisbook,youaregoingtobecomefluentin
this awesome code language and see it applied to a variety of examples. No type
declaration of methodology, parameters, functions, or variables (like in other languages)
arefoundinPythonmakingitscodeconciseandeasy.AsIsaidearlier,youcanusethe
language in everything if you want to build a website, make a game, or even create a
searchengine.ThebigplusofusingPythonis,anexplicitcompilerisnotnecessarysince
it’sanentirelyinterpretedlanguage(Perl,Shell,etc.).


File extension which is used by Python source file is “.py” and it is a case-sensitive
language, so “P” and “p” would be considered as two different variables. Also, Python
figuresoutthevariabletypeonitsown,forexample,ifyouputx=4andy=’Python’thenit
will consider x as an integer and y as a string. We are going to learn all these basics in
detailinfurtherchapters.Beforewemoveforward,afewimportantpointstoremember
are:

1.Forassigningavalue“=”isused,andforcomparison“==”isused.Example,
x=4,y=8,x==y
2.“print”isusedtoprintresults.
3.Allthemathematicaloperationslike+,-,*,/,%areusedwithnumbers
4. Variable is created when a value is assigned to it. Example, a=5 will create a
variablenamed“a”whichhasanintegervalueof5.Thereisnoneedtodefineit
beforehand.
5. “+” can also be used to concatenate two string. Example, z= “Hi”, z= z +


“Python”
6.Forlogicaloperations“and”,“or”,“not”areusedinsteadofsymbols.
We use three general data types: integer (by default for numbers), floats (a=3.125) and
string.Thestringisshownbyeither“”(doublequotes)or‘’(singlequotes).Wewilllook
atallthetypesofdatawithvariousexamplesintheupcomingchapters.

Let’slookatthestepbystepguidetoinstallPythononaWindowsoperatingsystem.As
mentionedearlier,ifyouareusinganotheroperatingsystemlikeUNIXorLinuxorMac
thenPythonshouldbeinstalledalreadyandreadytouse.Youhavetouse“%python”to
getthedetailsonLinux,press“CTRL+D”toexit.ForrunningitonUNIX,“%python
filename.py”isused.Pythonpromptswiththree“greaterthan”symbol(>>>).




Chapter2
InstallingPythonandSettinguptheEnvironment


Inthischapter,wearegoingtoseeastepbystepguidetodownloadandinstallthePython
language interpreter. After installation of the interpreter, we will integrate and set up
PythondevelopmentenvironmentwithEclipseIDE.
Python programming language is available for all of the three known platforms for
Windows,Linux/Unix,andMacOS.BelowarethelinksfromwherePythoninterpreters
canbedownloadedfortheseenvironments.

Windowsplatform
PythoninterpretercanbedownloadedforWindowsplatformusingthelinkbelow.
/>OptionsavailableonPythonwebsiteareasfollows:
Python3.4.4-2015-12-21
DownloadWindowsx86MSIInstaller
DownloadWindowsx86-64MSIinstaller
DownloadWindowshelpfile
DownloadWindowsdebuginformationfilesfor64-bitbinaries
DownloadWindowsdebuginformationfiles

Inthistutorial,wearegoingtouseWindowsplatformtoinstallPython3.4.4alongwith
EclipseIDEtosetupadevelopmentenvironment.

LINUX/UNIXplatform
IfyouarenotabletofindPythononyourLinuxorUnixOS,thenPythoninterpretercan



bedownloadedforLINUXorUNIXplatformfromthelinkbelow.
/>A different Linux version uses different package managers for installation of new
packages. For example, on Ubuntu, Python can be installed using the below command
fromtheterminal.

$sudoapt-getinstallpython3-minimal

Itisinstalledfromsourceusingthebelowcommand.
Download Gzipped source tarball from Python’s download URL:
/>Extractthetarball
tarxvfzPython-3.5.1.tgz
ConfigureandInstall:
cdPython-3.5.1
./configure—prefix=/opt/python3.5.1
make
sudomakeinstall

MacOSPlatform
PythoninterpretercanbedownloadedforMacOSplatformfromthelinkbelow.
/>OptionsavailableonPythonwebsiteareasfollows.
Python3.4.4-2015-12-21


DownloadMacOSX64-bit/32-bitinstaller
DownloadMacOSX32-biti386/PPCinstaller

StepstoinstallPythononWindowsPlatform
Pleasefollowthebelowsteps:
1. Check for Windows installer if it is 32-bit or 64-bit. Accordingly, download
PythonversionforWindowsplatformforthegivenlink.


2. Once downloaded, click on the installer. The below screen will be visible which
willtriggerPythoninstallationonWindows.



3. Choose the first option as “Install for all users” and click on the next button to
proceed.

4. Next,thesystemwillasktoselectthedestinationdirectory.Choosethedirectory
asshownbelowandclickonNextbutton.




5. Next, the system will ask to customize Python 3.4.4. Keep the default setup and
clickontheNextbuttonasshowninthebelowscreenshot.



6. Installer will start the installation which will take several minutes and the below
screenshotwillbevisibleduringthispointoftime.




7. Once Python interpreter installation is completed, click on the Finish button to
completetheinstallationonWindowsplatform.




StepstosetupPythondevelopmentenvironmentonEclipseIDE

Pleasefollowthebelowsteps:
1. DownloadtheEclipsefromthelinkbelow.Choosethelateststableversionofthe
Eclipseandmakesurethatifyourmachineis64-bitthenchose64-bitEclipse.In
thistutorial,EclipseMARS.1versionisused.
/>
2. Click on the elipse.exe to open the Eclipse which will ask to choose a local
directoryasitsworkspaceasshowninthebelowscreenshot.



3. ChooseorcreateadirectoryonanyavailabledriveandclickontheOKbuttonto
starteclipse.



4. OntheEclipse,navigateasHelp->InstallNewSoftware…



5. It will open a dialogue box in Eclipse as shown in the below screenshot. In the
textbox “work with:” enter the URL as and click on the
Addbutton.Next,selectthecheckboxas“PyDev”andclickontheNextbutton.



6. Next, the system will ask to read and accept or decline the license agreement.
Acceptthelicenseagreementinordertoproceedthecurrentsoftwareinstallation

andclickontheFinishbuttonasshowninthebelowscreenshot.


7. The step above will complete the installation of PyDev software on the Eclipse.
Afterinstallation,itwillprompttorestartEclipse.UponEclipserestart,thePython
developmentenvironmentisreadytouseonEclipse.



FirstPythonprojectonEclipse

Pleasefollowbelowsteps.
1. Left-hand side of Eclipse has Project Explorer. Right click in that region or
navigateasNew->Project.SelectPyDevfromtheWizardasshowninthebelow
screenshot.



2. SelectPyDevProjectoptionfromWizardandclickonnextbuttontoproceed.

3. It will open a PyDev project dialog box asking for Project name, project type,
grammarversionandinterpreterconfiguration.

4. Give the project name as “MyFirstPythonProject”, project type as Python, and
grammarversionas3.0-3.5.

5. ClickonthegivenlinktoconfigurethePythoninterpreterasshownbelow.Here
wejustneedtogivethepathofpython.exewhereweinstalledPythononCdrive.




6. ClickontheInterpreterlink;itwillaskforhowtoconfiguretheinterpretersince
weknowthePythoninstallationpath,therefore,select“ManualConfig”option.



7. Click on the “New” button present at the top right corner and in the opened
dialoguebox,entertheinterpreternameandtheinterpreterexecutablepath.Since
weareusingPythonversionas3.4.4,thereforeenterthenameas“Python3.4.4”
andexecutablepathasC:\Python34\python.exe.ClickOKbuttontocompletethis
step.




8. A new dialogue box will be opened as shown. This step will ask to select all
foldersthatarerequiredtobeaddedtotheSYSTEMPythonpath.Selectalland
clickontheOKbuttontocompletethisstep.


9. Next,clickontheApplybuttonandthentheOKbuttontocompletethesetupfor
Pythonfirstprojectasshowninthebelowscreenshot.




10.Lastly,clickontheFinishbuttontocompletefirst“PyDevProject”set
upinEclipseasshowninthebelowscreenshot.



11.Bythisstep,Pythonfirstprojectdirectorystructureandpathsetupare
readyasshowninthebelowscreenshot.




12.Atthesourcedirectory,rightclickandnavigateasNew->PyDev
Module.



13.ThiswillopenadialogueboxaskingtoenterpackageandPyDev
modulename.Enterthenameas“FirstPython”andclickontheFinishbuttonto
completethisstepasshowninthebelowscreenshot.



14.Thestepabovewillopenupanotherdialoguebox,askingyoutoselect
thetemplateforthePythonproject.Choosehere<Empty>andclickontheOK
button.



15.ThiswillopentheFirstPython.pyfilewherewecaneditandwritethe
Pythonprogramcodeasshowninthebelowscreenshot.Pythonprogramfileshave
anextensionas.py.


16.TorunthePythonprogramabove,pressCtrl+F11keys,itwillopenup



belowdialoguebox.Select“PythonRun”optionandclickOKbuttontocomplete
thisstep.








17. ThefinaloutputwillbedisplayedatthebottomoftheEclipseinthe
consoleasshowninthebelowscreenshot.


Thiscompletestheinstallation,environmentsetupandexecutionforfirstPythonprogram.
In the next chapter, we are going to learn about the various syntax used in Python
programming.



×