Tải bản đầy đủ (.pdf) (1,760 trang)

310690413-Raspberry-Pi-Teach-Yourself-Python-Programming-in-24-Hours-2016-pdf

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 (29.63 MB, 1,760 trang )


AboutThisE-Book
EPUBisanopen,industry-standardformatfore-books.However,supportforEPUB
anditsmanyfeaturesvariesacrossreadingdevicesandapplications.Useyourdeviceor
appsettingstocustomizethepresentationtoyourliking.Settingsthatyoucancustomize
oftenincludefont,fontsize,singleordoublecolumn,landscapeorportraitmode,and
figuresthatyoucanclickortaptoenlarge.Foradditionalinformationaboutthesettings
andfeaturesonyourreadingdeviceorapp,visitthedevicemanufacturer’sWebsite.
Manytitlesincludeprogrammingcodeorconfigurationexamples.Tooptimizethe
presentationoftheseelements,viewthee-bookinsingle-column,landscapemodeand
adjustthefontsizetothesmallestsetting.Inadditiontopresentingcodeand
configurationsinthereflowabletextformat,wehaveincludedimagesofthecodethat
mimicthepresentationfoundintheprintbook;therefore,wherethereflowableformat
maycompromisethepresentationofthecodelisting,youwillseea“Clickheretoview
codeimage”link.Clickthelinktoviewtheprint-fidelitycodeimage.Toreturntothe
previouspageviewed,clicktheBackbuttononyourdeviceorapp.


SamsTeachYourselfPython
ProgrammingforRaspberryPiin24
Hours
SECONDEDITION
RichardBlumand
ChristineBresnahan

800East96thStreet,Indianapolis,Indiana,46240USA


SamsTeachYourselfPythonProgrammingforRaspberryPiin24Hours,Second
Edition
Copyright©2016byPearsonEducation,Inc.


Allrightsreserved.Nopartofthisbookshallbereproduced,storedinaretrievalsystem,
ortransmittedbyanymeans,electronic,mechanical,photocopying,recording,or
otherwise,withoutwrittenpermissionfromthepublisher.Nopatentliabilityisassumed
withrespecttotheuseoftheinformationcontainedherein.Althougheveryprecautionhas
beentakeninthepreparationofthisbook,thepublisherandauthorassumeno
responsibilityforerrorsoromissions.Norisanyliabilityassumedfordamagesresulting
fromtheuseoftheinformationcontainedherein.
ISBN-13:978-0-672-33764-2
ISBN-10:0-672-33764-9
LibraryofCongressControlNumber:2015914178
PrintedintheUnitedStatesofAmerica
FirstPrintingDecember2015
Editor-in-Chief
GregWiegand
ExecutiveEditor
RickKughen
DevelopmentEditor
MarkRenfrow
ManagingEditor
SandraSchroeder
ProjectEditor
SethKerney
CopyEditor
MeganWade-Taxter
Indexer
KenJohnson
Proofreader
PaulaLowell
TechnicalEditor
KevinRyan

PublishingCoordinator
CindyTeeters
BookDesigner
MarkShirar
Compositor


codeMantra
Trademarks
Alltermsmentionedinthisbookthatareknowntobetrademarksorservicemarkshave
beenappropriatelycapitalized.SamsPublishingcannotattesttotheaccuracyofthis
information.Useofaterminthisbookshouldnotberegardedasaffectingthevalidityof
anytrademarkorservicemark.
WarningandDisclaimer
Everyefforthasbeenmadetomakethisbookascompleteandasaccurateaspossible,but
nowarrantyorfitnessisimplied.Theinformationprovidedisonan“asis”basis.The
authorsandthepublishershallhaveneitherliabilitynorresponsibilitytoanypersonor
entitywithrespecttoanylossordamagesarisingfromtheinformationcontainedinthis
bookorfromtheuseofprogramsaccompanyingit.
SpecialSales
Forinformationaboutbuyingthistitleinbulkquantities,orforspecialsalesopportunities
(whichmayincludeelectronicversions;customcoverdesigns;andcontentparticularto
yourbusiness,traininggoals,marketingfocus,orbrandinginterests),pleasecontactour
corporatesalesdepartmentator(800)382-3419.
Forgovernmentsalesinquiries,pleasecontact
ForquestionsaboutsalesoutsidetheU.S.,pleasecontact


ContentsataGlance
Introduction

PartI:PythonProgrammingontheRaspberryPi
HOUR1SettingUptheRaspberryPi
2UnderstandingtheRaspbianLinuxDistribution
3SettingUpaProgrammingEnvironment
PartII:PythonFundamentals
HOUR4UnderstandingPythonBasics
5UsingArithmeticinYourPrograms
6ControllingYourProgram
7LearningAboutLoops
PartIII:AdvancedPython
HOUR8UsingListsandTuples
9DictionariesandSets
10WorkingwithStrings
11UsingFiles
12CreatingFunctions
13WorkingwithModules
14ExploringtheWorldofObject-OrientedProgramming
15EmployingInheritance
16RegularExpressions
17ExceptionHandling
PartIV:GraphicalProgramming
HOUR18GUIProgramming
19GameProgramming
PartV:BusinessProgramming
HOUR20UsingtheNetwork
21UsingDatabasesinYourProgramming
22WebProgramming
PartVI:RaspberryPiPythonProjects
HOUR23CreatingBasicPi/PythonProjects



24WorkingwithAdvancedPi/PythonProjects
Appendixes
ALoadingtheRaspbianOperatingSystemontoanSDCard
BRaspberryPiModelsSynopsis
Index


TableofContents
Introduction
ProgrammingwithPython
WhoShouldReadThisBook?
ConventionsUsedinThisBook
PartI:PythonProgrammingontheRaspberryPi
HOUR1:SettingUptheRaspberryPi
ObtainingaRaspberryPi
AcquiringaRaspberryPi
DeterminingtheNecessaryPeripherals
NiceAdditionalPeripherals
DecidingHowtoPurchasePeripherals
GettingYourRaspberryPiWorking
TroubleshootingYourRaspberryPi
Summary
Q&A
Workshop
HOUR2:UnderstandingtheRaspbianLinuxDistribution
LearningAboutLinux
InteractingwiththeRaspbianCommandLine
InteractingwiththeRaspbianGUI
TheLXDEGraphicalInterface

Summary
Q&A
Workshop
HOUR3:SettingUpaProgrammingEnvironment
ExploringPython
CheckingYourPythonEnvironment
InstallingPythonandTools
LearningAboutthePythonInterpreter
LearningAboutthePythonInteractiveShell


LearningAboutthePythonDevelopmentEnvironment
CreatingandRunningPythonScripts
KnowingWhichTooltoUseandWhen
Summary
Q&A
Workshop
PartII:PythonFundamentals
HOUR4:UnderstandingPythonBasics
ProducingPythonScriptOutput
FormattingScriptsforReadability
UnderstandingPythonVariables
AssigningValuetoPythonVariables
LearningAboutPythonDataTypes
AllowingPythonScriptInput
Summary
Q&A
Workshop
HOUR5:UsingArithmeticinYourPrograms
WorkingwithMathOperators

CalculatingwithFractions
UsingComplexNumberMath
GettingFancywiththemathModule
UsingtheNumPyMathLibraries
Summary
Q&A
Workshop
HOUR6:ControllingYourProgram
WorkingwiththeifStatement
GroupingMultipleStatements
AddingOtherOptionswiththeelseStatement
AddingMoreOptionsUsingtheelifStatement
ComparingValuesinPython


CheckingComplexConditions
NegatingaConditionCheck
Summary
Q&A
Workshop
HOUR7:LearningAboutLoops
PerformingRepetitiveTasks
UsingtheforLoopforIteration
UsingthewhileLoopforIteration
CreatingNestedLoops
Summary
Q&A
Workshop
PartIII:AdvancedPython
HOUR8:UsingListsandTuples

IntroducingTuples
IntroducingLists
UsingMultidimensionalListstoStoreData
WorkingwithListsandTuplesinYourScripts
CreatingListsbyUsingListComprehensions
WorkingwithRanges
Summary
Q&A
Workshop
HOUR9:DictionariesandSets
UnderstandingPythonDictionaryTerms
ExploringDictionaryBasics
ProgrammingwithDictionaries
UnderstandingPythonSets
ExploringSetBasics
ObtainingInformationfromaSet
ModifyingaSet


ProgrammingwithSets
Summary
Q&A
Workshop
HOUR10:WorkingwithStrings
TheBasicsofUsingStrings
UsingFunctionstoManipulateStrings
FormattingStringsforOutput
Summary
Q&A
Workshop

HOUR11:UsingFiles
UnderstandingLinuxFileStructures
ManagingFilesandDirectoriesviaPython
OpeningaFile
ReadingaFile
ClosingaFile
WritingtoaFile
Summary
Q&A
Workshop
HOUR12:CreatingFunctions
UtilizingPythonFunctionsinYourPrograms
ReturningaValue
PassingValuestoFunctions
HandlingVariablesinaFunction
UsingListswithFunctions
UsingRecursionwithFunctions
Summary
Q&A
Workshop
HOUR13:WorkingwithModules


IntroducingModuleConcepts
ExploringStandardModules
LearningAboutPythonModules
CreatingCustomModules
Summary
Q&A
Workshop

HOUR14:ExploringtheWorldofObject-OrientedProgramming
UnderstandingtheBasicsofObject-OrientedProgramming
DefiningClassMethods
SharingYourCodewithClassModules
Summary
Q&A
Workshop
HOUR15:EmployingInheritance
LearningAbouttheClassProblem
UnderstandingSubclassesandInheritance
UsingInheritanceinPython
UsingInheritanceinPythonScripts
Summary
Q&A
Workshop
HOUR16:RegularExpressions
WhatAreRegularExpressions?
WorkingwithRegularExpressionsinPython
Thematch()Function
Thesearch()Function
Thefindall()andfinditer()Functions
DefiningBasicPatterns
UsingAdvancedRegularExpressionsFeatures
WorkingwithRegularExpressionsinYourPythonScripts
Summary


Q&A
Workshop
HOUR17:ExceptionHandling

UnderstandingExceptions
HandlingExceptions
HandlingMultipleExceptions
Summary
Q&A
Workshop
PartIV:GraphicalProgramming
HOUR18:GUIProgramming
ProgrammingforaGUIEnvironment
ExaminingPythonGUIPackages
UsingthetkinterPackage
ExploringthetkinterWidgets
Summary
Q&A
Workshop
HOUR19:GameProgramming
UnderstandingGameProgramming
LearningAboutGameTools
SettingUpthePyGameLibrary
UsingPyGame
LearningMoreAboutPyGame
DealingwithPyGameAction
Summary
Q&A
Workshop
PartV:BusinessProgramming
HOUR20:UsingtheNetwork
FindingthePythonNetworkModules
WorkingwithEmailServers



WorkingwithWebServers
LinkingProgramsUsingSocketProgramming
Summary
Q&A
Workshop
HOUR21:UsingDatabasesinYourProgramming
WorkingwiththeMySQLDatabase
UsingthePostgreSQLDatabase
Summary
Q&A
Workshop
HOUR22:WebProgramming
RunningaWebServeronthePi
ProgrammingwiththeCommonGatewayInterface
ExpandingYourPythonWebpages
ProcessingForms
Summary
Q&A
Workshop
PartVI:RaspberryPiPythonProjects
HOUR23:CreatingBasicPi/PythonProjects
ThinkingAboutBasicPi/PythonProjects
DisplayingHDImagesviaPython
PlayingMusic
Summary
Q&A
Workshop
HOUR24:WorkingwithAdvancedPi/PythonProjects
ExploringtheGPIOInterface

UsingtheRPi.GPIOModule
ControllingGPIOOutput
DetectingGPIOInput


Summary
Q&A
Workshop
Appendixes
APPENDIXA:LoadingtheRaspbianOperatingSystemontoanSDCard
DownloadingNOOBS
VerifyingNOOBSChecksum
UnpackingtheNOOBSZipFile
FormattingtheMicroSDCard
CopyingNOOBStoaMicroSDCard
APPENDIXB:RaspberryPiModelsSynopsis
RaspberryPi2ModelB
RaspberryPi1ModelB+
RaspberryPi1ModelA+
OlderRaspberryPiModels
Index


AbouttheAuthors
RichardBlumhasworkedintheITindustryformorethan30yearsasanetworkand
systemsadministrator,managingMicrosoft,Unix,Linux,andNovellserversfora
networkwithmorethan3,500users.Hehasdevelopedandteachesprogrammingand
LinuxcoursesviatheInternettocollegesanduniversitiesworldwide.Richhasamaster’s
degreeinmanagementinformationsystemsfromPurdueUniversityandistheauthorof
severalLinuxbooks,includingLinuxCommandLineandShellScriptingBible

(coauthoredwithChristineBresnahan);LinuxforDummies,NinthEdition;and
ProfessionalLinuxProgramming(coauthoredwithJonMasters).Whenhe’snotbusy
beingacomputernerd,Richenjoysspendingtimewithhiswife,Barbara,andtwo
daughters,KatieJaneandJessica.
ChristineBresnahanstartedworkingintheITindustrymorethan30yearsagoasa
systemadministrator.ChristineiscurrentlyanadjunctprofessoratIvyTechCommunity
CollegeinIndianapolis,Indiana,teachingPythonprogramming,Linuxsystem
administration,andLinuxsecurityclasses.ChristineproducesUnix/Linuxeducational
materialandistheauthorofLinuxBible,EighthEdition(coauthoredwithChristopher
Negus)andLinuxCommandLineandShellScriptingBible(coauthoredwithRichard
Blum).ShehasbeenanenthusiasticownerofaRaspberryPisince2012.


Dedication
TotheLordGodAlmighty.
“Iamthevine,youarethebranches;hewhoabidesinMeandIinhim,
hebearsmuchfruit,forapartfromMeyoucandonothing.”
—John15:5


Acknowledgments
First,allgloryandpraisegotoGod,whothroughHisSon,JesusChrist,makesallthings
possibleandgivesusthegiftofeternallife.
ManythanksgotothefantasticteamofpeopleatSamsPublishingfortheiroutstanding
workonthisproject.ThankstoRickKughen,theexecutiveeditor,forofferingusthe
opportunitytoworkonthisbookandkeepingthingsontrack.Wearegratefulto
developmenteditorMarkRenfrow,whoprovideddiligenceinmakingourworkmore
presentable.Thankstotheproductioneditor,SethKerney,formakingsurethebookwas
produced.Manythankstothecopyeditor,MeganWade-Taxter,forherendlesspatience
anddiligenceinmakingourworkreadable.Also,weareindebtedtoourtechnicaleditor,

KevinE.Ryan,whoputinmanylonghoursdouble-checkingallourworkandkeepingthe
booktechnicallyaccurate.
ThankstoTonyaofTonyaWittigPhotography,whocreatedincrediblepicturesofour
RaspberryPisandwasverypatientintakingallthephotoswewantedforthebook,andto
thetalentedDanielAnez(theanez.com)forhisillustrationwork.Wewouldalsoliketo
thankCaroleJelenatWatersideProductions,Inc.,forarrangingthisopportunityforusand
forhelpingusoutinourwritingcareers.
Christinewouldalsoliketothankherstudent,PaulBohall,forintroducinghertothe
RaspberryPi,andherhusband,Timothy,forhisencouragementtopursuethe“geeky
stuff”studentsintroduceherto.


WeWanttoHearfromYou!
Asthereaderofthisbook,youareourmostimportantcriticandcommentator.Wevalue
youropinionandwanttoknowwhatwe’redoingright,whatwecoulddobetter,what
areasyou’dliketoseeuspublishin,andanyotherwordsofwisdomyou’rewillingto
passourway.
Wewelcomeyourcomments.Youcanemailorwritetoletusknowwhatyoudidordidn’t
likeaboutthisbook—aswellaswhatwecandotomakeourbooksbetter.
Pleasenotethatwecannothelpyouwithtechnicalproblemsrelatedtothetopicofthis
book.
Whenyouwrite,pleasebesuretoincludethisbook’stitleandauthoraswellasyourname
andemailaddress.Wewillcarefullyreviewyourcommentsandsharethemwiththe
authorandeditorswhoworkedonthebook.
Email:
Mail:SamsPublishing
ATTN:ReaderFeedback
800East96thStreet
Indianapolis,IN46240USA



ReaderServices
Visitourwebsiteandregisterthisbookatinformit.com/registerforconvenientaccessto
anyupdates,downloads,orerratathatmightbeavailableforthisbook.


Introduction
OfficiallylaunchedinFebruary2012,theRaspberryPipersonalcomputertooktheworld
bystorm,sellingoutthe10,000availableunitsimmediately.Itisaninexpensivecredit
card–sizedexposedcircuitboard,afullyprogrammablePCrunningthefreeopen-source
Linuxoperatingsystem.TheRaspberryPicanconnecttotheInternet,canbepluggedinto
aTV,and—withthelatestversion2—runsonafastARMprocessor,rivalingthe
performanceofmanytabletdevices,allforaround$35.
Originallycreatedtosparkschoolchildren’sinterestincomputers,theRaspberryPihas
caughttheattentionofhomehobbyists,entrepreneurs,andeducatorsworldwide.
Estimatesputthesalesfiguresaround6millionunitsasofJune2015.
TheofficialprogramminglanguageoftheRaspberryPiisPython.Pythonisaflexible
programminglanguagethatrunsonalmostanyplatform.Thus,aprogramcanbecreated
onaWindowsPCorMacandrunontheRaspberryPi,andviceversa.Pythonisan
elegant,reliable,powerful,andverypopularprogramminglanguage.MakingPythonthe
officialprogramminglanguageofthepopularRaspberryPiwasgenius.

ProgrammingwithPython
Thegoalofthisbookistohelpguidebothstudentsandhobbyiststhroughusingthe
PythonprogramminglanguageonaRaspberryPi.Youdon’tneedtohaveany
programmingexperiencetobenefitfromthisbook;wewalkthroughallthenecessary
stepsingettingyourPythonprogramsupandrunning!
PartI,“PythonProgrammingontheRaspberryPi,”walksthroughthecoreRaspberryPi
systemandhowtousethePythonenvironmentthat’salreadyinstalledinit.Hour1,
“SettingUptheRaspberryPi,”demonstrateshowtosetupaRaspberryPisystem,and

theninHour2,“UnderstandingtheRaspbianLinuxDistribution,”wetakeacloserlookat
Raspbian—theLinuxdistributiondesignedspecificallyfortheRaspberryPi.Hour3,
“SettingUpaProgrammingEnvironment,”examinesthevariouswaysyoucanrunyour
PythonprogramsontheRaspberryPi,anditgoesthroughsometipsonhowtobuildyour
programs.
PartII,“PythonFundamentals,”focusesonthePython3programminglanguage.Python
v3isthenewestversionofPythonandisfullysupportedintheRaspberryPi.Hours4–7
takeyouthroughthebasicsofPythonprogramming,fromsimpleassignmentstatements
(Hour4,“UnderstandingPythonBasics”),arithmetic(Hour5,“UsingArithmeticinYour
Programs”),andstructuredcommands(Hour6,“ControllingYourProgram”),tocomplex
structuredcommands(Hour7,“LearningAboutLoops”).
Hour8,“UsingListsandTuples,”andHour9,“DictionariesandSets,”kickoffPartIII,
“AdvancedPython,”showinghowtousesomeofthefancierdatastructuressupportedby
Python—lists,tuples,dictionaries,andsets.You’llusethesealotinyourPython
programs,soithelpstoknowallaboutthem!
InHour10,“WorkingwithStrings,”wetakealittleextratimetogooverhowPython
handlestextstrings.StringmanipulationisahallmarkofthePythonprogramming


language,sowewanttomakesureyou’recomfortablewithhowthatallworks.
Afterthatprimer,wewalkthroughsomemorecomplexconceptsinPython:usingfiles
(Hour11,“UsingFiles”),creatingyourownfunctions(Hour12,“CreatingFunctions”),
creatingyourownmodules(Hour13,“WorkingwithModules”),object-orientedPython
programming(Hour14,“ExploringtheWorldofObject-OrientedProgramming”),
inheritance(Hour15,“EmployingInheritance”),regularexpressions(Hour16,“Regular
Expressions”),andworkingwithexceptions(Hour17,“ExceptionHandling”).
PartIV,“GraphicalProgramming,”isdevotedtousingPythontocreatereal-world
applications.Hour18,“GUIProgramming,”discussesGUIprogrammingsoyoucan
createyourownwindowsapplications.Hour19,“GameProgramming,”introducesyouto
theworldofPythongameprogramming.

PartV,“BusinessProgramming,”takesalookatsomebusiness-orientedapplicationsyou
cancreate.InHour20,“UsingtheNetwork,”welookathowtoincorporatenetwork
functionssuchasemailandretrievingdatafromwebpagesintoyourPythonprograms.
Hour21,“UsingDatabasesinYourProgramming,”showshowtointeractwithpopular
Linuxdatabaseservers,andHour22,“WebProgramming,”demonstrateshowtowrite
PythonprogramsyoucanaccessfromacrosstheWeb.
PartVI,“RaspberryPiPythonProjects,”walksthroughPythonprojectsthatfocus
specificallyonfeaturesfoundontheRaspberryPi.Hour23,“CreatingBasicPi/Python
Projects,”showshowtousetheRaspberryPivideoandsoundcapabilitiestocreate
multimediaprojects.Hour24,“WorkingwithAdvancedPi/PythonProjects,”explores
connectingyourRaspberryPiwithelectroniccircuitsusingtheGeneralPurpose
Input/Output(GPIO)interface.

WhoShouldReadThisBook?
ThisbookisaimedatreadersinterestedingettingthemostfromtheirRaspberryPisystem
bywritingtheirownPythonprograms,includingthesethreegroups:
StudentsinterestedinaninexpensivewaytolearnPythonprogramming
HobbyistswhowanttogetthemostoutoftheirRaspberryPisystem
EntrepreneurslookingforaninexpensiveLinuxplatformtouseforapplication
deployment
Ifyouarereadingthisbook,youarenotnecessarilynewtoprogramming,butyoumight
benewtousingPythonprogramming,oratleastPythonprogrammingintheRaspberryPi
environment.ThisbookwillprovetobeagoodresourceforquicklyfindingPython
featuresandmodulesthatyoucanuseforalltypesofprograms.

ConventionsUsedinThisBook
Tomakeyourlifeeasier,thisbookincludesvariousfeaturesandconventionsthathelpyou
getthemostoutofthisbookandoutofyourRaspberryPi:



Thisbookalsousesthefollowingboxestodrawyourattentiontoimportantorinteresting
information:
BytheWay
BytheWayboxespresentasidesthatgiveyoumoreinformationaboutthecurrent
topic.Thesetidbitsprovideextrainsightsthatofferbetterunderstandingofthetask.
DidYouKnow?
DidYouKnowboxescallyourattentiontosuggestions,solutions,orshortcutsthat
areoftenhidden,undocumented,orjustextrauseful.
WatchOut!
WatchOut!boxesprovidecautionsorwarningsaboutactionsormistakesthatbring
aboutdatalossorotherseriousconsequences.


PartI:PythonProgrammingonthe
RaspberryPi


Hour1.SettingUptheRaspberryPi
WhatYou’llLearninThisHour:
WhatistheRaspberryPi?
HowtogetaRaspberryPi
WhatperipheralsyouneedfortheRaspberryPi
HowtogetaRaspberryPiworking
HowtotroubleshootaRaspberryPi
ThislessonintroducestheRaspberryPi:whatitis,itshistory,andwhyyoushouldlearn
howtoprograminPythononit.Bytheendofthishour,youwillknowwhichperipherals
areneededforaRaspberryPiandhowtogetoneupandrunning.

ObtainingaRaspberryPi
ARaspberryPiisaveryinexpensive,fullyprogrammablecomputerthatissmallenough

tofitintothepalmofyourhand(seeFigure1.1).AlthoughtheRaspberryPiissmallin
size,itismightyinpotential.Youcanuseitlikearegulardesktopcomputerorcreatea
super-coolprojectwithit.Forexample,youcoulduseaRaspberryPitosetupyourvery
ownhome-basedcloudstorageserver.

Figure1.1TheRaspberryPi2ModelB.Notethepaperclipforscale.


×