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

Python programming up and running with python easy to learn training course for beginners

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 (803.6 KB, 168 trang )


PythonMadeEasy
UpandRunningwithPython




Publishedby
AzElitePublishingInc.
ISBN-13:
978-1502393470


ISBN-10:
1502393476

ManufacturedinCanada
PublishedsimultaneouslyinCanada
1093830234


Nopartofthispublicationmaybreproducedortransmittedinanyformbyanymeans,
electronic,mechanical,photocopying,recording,orotherwise,withoutthepriorwritten
permissionofthepublisher.Forinformationongettingpermissionforreprintsand
experts,contact
NoticeofLiability:
Theinformationinthisbookisdistributiononas“AsIs”Basis,withoutwarranty.While
everyprecautionhasbeentakeninthepreparationofthisbook,neithertheauthornor
publishershallhaveanyliabilitytoanypersonorentitywithrespecttoanyloseor
damagecausedorallegedtobecauseddirectlyorindirectlybytheinstructionscontained
inthisbookorbythecomputersoftwareandhardwareproductsdescribedinit.






FREEGuruLevelTrainingForBeginners
(Value$37permonth,YoursFREE)



TABLEOFCONTENTS

PythonMadeEasy
Chapter1:JumpingintoPython
TheHistoryofPython
BenefitsofPython
Chapter2:GettingStarted
InstallingPythonandanIDE
InstallinganIDE
ExampleProgram
Chapter3:BuildingOurFirstPrograms
Indentation
Variables
Numbers
Strings
Operators
PROJECT:Variables
ConditionalOperators(If/ElseStatements)
IfStatement
If/ElseStatement.
NestedStatements

PROJECT:DecisionMaking
Loops
WhileLoops
ForLoops
PROJECT:Loops
BONUS
Chapter4:ListsandTuples
WhatAreLists?
AccessingItems


BooleanStatementsandLists
CreatingTuples
CreatingLists
Chapter5:Functions
WhatAreFunctions?
DefiningFunctions
ParametersandReturningFunctions
ExampleFunction
PassingParametersinFunctions
VariablesinFunctions
Chapter6:Classes
WhatAreClasses?
DefiningandCreatingClasses
ClassTerminology
UsingClassesandSelf
Chapter7:ImportingModules
WhatAreModules?
DefiningModules
Chapter8:FileI/O

WhatisFileI/O?
OpeningFiles
Cursor
OtherI/OFunctions
tell()
readline()
write()
close()
Chapter9:ErrorHandling
WhatIsExceptionHandling?
BugsandHumanErrors
Exceptions
Conclusion


BONUS
BONUS


Introduction
“WhenIgotstarted,Iwasasideshow.AtmyfirstConsumerElectronicsShow,in1977in
Chicago,peoplecamefromalloverthefloortoseethe‘ladyprogrammer.’Theyhadme
dressedinaturquoiselabcoatwithmynameembroideredonthepocket.”-Brenda
Laurel

Hello,

WelcometoPythonmadeeasy.

BeforeIresumetotellyouaboutPythonandPythonprogrammingI’dliketotellyouthat

I’vebeenthroughthepainsandstrugglesthatanyaspiringprogrammergoesthrough.
Goingthroughbooksontheconceptwasdifficult-notbecauseIdidn’tunderstandthembutbecausetherewassomuchtechnicaljargonthatIhadtoreadthesamething4times
untiltheauthorofthebookgotthroughtome.

You’llseethatseveralbooksonprogrammingusealotoftechnicaljargonwhichalienates
areaderandespeciallyonewhohasnoideaaboutPythonorprogrammingatall

OnmypathtolearningprogrammingwithPythonIlearnedthattheprogramisn’tdifficult
tounderstand.It’sactuallyoneoftheeasiestprogramminglanguagesthatI’vecome
across.ItiseasytocomprehendandthecodesarefareasierthanI’dexpectedthemtobe.
So,I’vesimplifiedcertainconceptsandexplainedvariouscodesandconcepts,inthis
book,sothatanylaymancanunderstandPythonprogramming.

I’veincludedexercisesinthisbookthatwillhelpyoufamiliarizeyourselfwithPython
programmingbecauseIdiscoveredthatdoingsuchexerciseshelpsreadersgetahangof
theprogramalotfaster.

SinceIamsomeonewhocanrelatetothepainthatanaspiringprogrammergoesthrough,
Ihavewrittenthisbookforyouwhilekeepingyourwoesandworriesinmind.

Whenyoureadthisbookyouwillseethatprogrammingisn’tastechnicalanddifficultas
peoplemakeitouttobe.Youdon’tevenneedtoknowthebasicsofprogrammingbecause
Ihavedividedthisbookintoseveralchaptersandsectionsthatwillhelpyouunderstand
theprogramalotfaster.Thiswayyoucanlearnprogrammingfromscratchandlearn


everythingthatyouneedtoknowasaPythonprogrammer.

So,ifyouarelearningtousethisprogramminglanguage,allyouneedtodoistofireup
yourlaptopandstartreadingthisbook.ClickonthevariouslinksI’veaddedheretohelp

yougetmorecontentonPythonprogramming.
Ihavealsoaddedvariousexercisesattheendofdifferentchapters.Reviseyourconcepts
withtheseexercisesandifthere’sanythingthatyou’vemissedouton,orskipped,youcan
alwaysgobackandreadthechapteralloveragain.
Youwillcomeacrossvariouscodesthatwillshowyouhowyoucanmakecodeswith
Python.Gothroughthesecodesandtrytomakeyourowntoo.
Ihopethatyouenjoyyourjourneyandthatthisbookassistsyouonyourpath,too.

Thankyou,fordownloadingthisbook.Now,let’sgettothemainpart!
GOODLUCK!



Chapter1: JumpingintoPython

“Ibelievethatmoviesarefastbecomingantiqueanddinosauricasamedium.Filmisa
mediumfortheover-40sandtelevisionhasgonethesameway.Ifyou’regoingtolook
towardsthenewgeneration,thenofcourseyou’regoingtohavetobealotmorerandom,
spontaneous,irreverentandprovocativewithyourprogramming.”MalcolmMcLaren


So,youareinterestedinlearningPython?Pythonisacuttingedgeprogramminglanguage
that is geared toward simplicity. Python was created to be written productively with
maximum readability, without having to sacrifice quality. If you’re reading this book,
you’ve probably already researched Python and have a good idea of what the language
could potentially offer. Well, the hype is true. The language has received increased
attentioninrecentyearsforagoodreason–it’seasytolearn,it’sextremelyreadable,and
thesoftwarequalityitcreatesisunmatched.

Evenifyouhaveneverwrittenasinglelineofcodeinyourlife,Pythonisanexcellent

placetostartlearning.Onegreatthingaboutprogrammingisthatalllanguagesarevery
similar to one another. Sure, they all have different syntax and different features, but
generally programming code transplanted from one language to another will look very
similar.Ifyoulearntheintroductoryconceptsinonelanguage,youcaneasilyapplyitto
other languages as well. Likewise, if you are coming to Python with a background in a
differentlanguage,youshouldfindthetransitionrelativelyeasy.

YourtypicalPythonprogramwillcontainone-thirdthecodeofyourtypicalC++orJava
program,whichisoneofthereasonswhyithasbecomesopopularinrecentyears.There
issimplylesscode(withoutsacrificingthereadabilityofthelanguage),andthisleadsto
less debugging and fewer errors to sort out. Python can be used to program virtually
anything.



TheHistoryofPython
Python was first created in the late 1980s by Guido van Rossum at CWI, located in the
Netherlands. In the beginning, the development of the language started as a hobby for
Rossum,originallymeanttokillsometimeduringawintervacation.The2ndversionof
thelanguage,Python2.0wasreleasedin2000,kickstartingitspopularity.Thereleaseof
thesecondversioncamewithincreasedtransparencyandcommunityparticipationinthe
developmentprocess.Python3madeitsdebutin2008,andoriginallywasnotbackwardscompatible,whichhindereditsgrowth.Sincethen,thelanguagehasbeenbackportedto
workwithpreviousversionsofthelanguage.InthisbookwewillbecoveringPython2
exclusively,asPython3hasnotbeenadoptedbymostlargeorganizationsatthistime.


BenefitsofPython

Python was originally developed to be a simpler, more readable programming language
that didn’t sacrifice functionality. Today Python is more popular than ever, and has

becomeknownfor;

Software Quality. Python code is stripped down. It’s simple, but its
efficient.Forthisreason,programswritteninPythonaretypicallyahigher
levelofquality.
Portability. Pythonasalanguagehasn’tchangedallofthatmuchoverthe
yearsandforthatreason,itisextremelyportable.Youcouldcopycodefrom
aprogramwritten10yearsago,andpasteitintoaprogramtodaywithoutan
issue.
Library Support. Libraries are community-created, pre-built functions.
There is nearly an unlimited number of Python libraries available today,
eachbringingitsownbenefitstothetable.
It’s fun. Python strips the code down and uses indentations instead of
bracketstodeterminewhatisrunandwhen.This,combinedwithitsbuilt-in
toolsetmakeitajoytocode,whichhasbroughtmanynewusersonboard.



Pythonisalsoanexcellentprogramminglanguageforthoseofyouwhoarelearning
programmingoraboutprogramminglanguagesforthefirsttime.YouwillfindthatPython
isaprogramminglanguagethatteachesyoutowritecodesthatcanbereadeasily.Python
recognizestheimportancesofreadability.Thisiswhyreadabilityandtersecodesarepart
oftheprogram.

ThebestpartaboutPythonisthatitisveryeasytounderstand-notjustforbeginnersor
intermediatesbutalsoforthosewhoarelearningaboutprogrammingfromscratch.Thisis
agreatprogramminglanguageandonethatyouwillhaveonyourtipswithinafewweeks,
ifyouarepersistentandconsistent,too.

I’vealwayspromotedthelanguageandinsistthatanyonewhowantstogetabasicideaof

whatprogrammingisallaboutshouldstartbylearningPython.Thisprogramming
languageisalsobeneficialinthelongrun.You’llfindyourselfenjoyingprogrammingand
youwon’tgetasfrustratedasyoudoormightwhenlearningvariousotherprogramming
languageseither.ThisiswhyseveralprogrammerswhohaveshiftedtoPython,fromother
programminglanguages,feelhappierandaremoreproductive,too.

Writingcodeswiththeprogramminglanguageisalotoffuntoo.Youcanmakereadable
codesthatareeasytomaintainormodifyaswell.

So,ifyouwanttogetintoprogrammingandunderstandhowtomakecodes,Pythonis
yourbestfriend.ItisusedwidelyandseveralprogrammerspreferPythonoverother
programminglanguages,too.

Allinall,anyonewantingtolearnprogrammingorcodingshouldstartbylearningPython
andthen,moveontootherprogramminglanguagesoncethey’vemasteredthisprogram.



Summary

Thischapterdiscussesthefollowing:



HowPythonwascreated
Thebenefitsoftheprogramminglanguage
WhybeginnersshouldlearntoprogramwithPython
WhatmakesPythononeoftheeasiestprogramminglanguagesforanyoneaspiring
tobecomeaprogrammer














Chapter2:GettingStarted
“PythonhasbeenanimportantpartofGooglesincethebeginning,andremainssoasthe
systemgrowsandevolves.TodaydozensofGoogleengineersusePython,andwe’re
lookingformorepeoplewithskillsinthislanguage.”-PeterNorvig,directorofsearch
atGoogle.

Inthischapteryouwilllearn:


WhatistheIntegratedDevelopmentEnvironment
Howtomakeasampleprogram?

ItstimetogettoknowPython!Therewillbeafewresourcesthatyouneedtoknowabout
beforewedivehead-firstintothecode.We’llstartbyinstallingthebestIDEforPython
use,PyCharm.


IntegratedDevelopmentEnvironment


IfyoualreadyknowaboutIDEs,feelfreetoskiponthissection.Ifyoudonot,I’dadvise
youtoreaditfirst.

Regardless of what programming language you go for, you will need an IDE (an
abbreviation for Integrated Development Environment). An IDE provides programmers
withthetoolssheorheneeds:

TheSourceCodeEditor-thisisatexteditorprogramthatcanbeusedtoeditthe
sourcecodesofvariousprogramsonyourcomputer.
Buildautomationtools-thesetoolsareusedforbuildautomation.Buildautomation
is something that programmers do quite frequently. These tools enable you to
compile sources codes in the form of binary codes, running automated tests and
suchlike.
Debugger-youwillalwayscomeacrosssomebugortheother.Thedebuggerhelps
youdetectandthen,getridofthesebugssothatthecomputerprogramisfreeof
bugsanderrors.


InstallingPythonandanIDE


Pythonisrelativelyeasytoinstall,anddoesn’trequireawholelotofknowledge.Navigate
tothedownloadpagelocatedhere:

/>
This is the most commonly used version of Python. Make sure that you download the
correctfile,basedonyouroperatingsystem.Someoperatingsystemsmightnotbecapable
ofsupportingaparticularversionoftheprogramminglanguage.


Opentheinstallationfileandclick“Installforallusers.”


InstallinganIDE


ForanIDE,wewillbeusingPyCharm.Youcanaccesstheirdownloadpagehere:

/>
PyCharmisoneofthemostpopularIDE’sforPython.It’ssimple,easytouse,andcomes
with a built in command prompt, which truly simplifies things for beginners. The best
featureisthatthecommunityeditionisavailablecompletelyforfree,offeringallofthe
standardfeaturesforPythondevelopment.Makesuretoselectyouroperatingsystemfrom
thetabsatthetopofthepagebeforedownloading.Yourdownloadwillbemorethan100
MB,soitcouldtakesometimetocomplete.Theinstallationprocessisrelativelystraight
forward.


ExampleProgram


You’llbeshockedbyhowlittlecodeisactuallyrequiredwhenprogramminginPython.
Comparedtootherlanguages,youmightseehalf(orless)ofthetotalnumberoflinesof
code.Butdon’tmistakethatforalackofdepth.Pythonisrobust,withenoughfeaturesfor
companieslikeGoogleandFacebooktochoosePythonasaprimarylanguageforsomeof
theirlargestbusinessprocesses.

RememberthatPythoninitssimplestformisnothingmorethanatextfilewithPython
statements.IfyouarecomingtoPythonfromC#andothersimilarlanguages,executing
filesisabitdifferentinPython,andoftenalessvisualprocess.


Here I will walk you through the creation of a sample program. It will be your typical
“Hello,World”openerthatyou’velikelyseenbefore.

Step1:OpenPyCharm.

Step2:GotoFile>NewProject

Step3:Inthe“Projectname:”section,enter“HelloPythonWorld”,thenclickOK.Make
sureyouhavethecorrectinterpreterselected.Yourscreenshouldlooklikethis:













Step4: Intheprojectwindow,rightclickonthefoldernamed“HelloPythonWorld”and


select
New >
Python
File.

When
prompted,namethefile“HelloP”.

Step5:Copyandpastethefollowingcodeintothetexteditor:

print“Hello,World!”

Step6: Inthe“Run”Menu,click“Run”.

Step7: Youwillbepromptedtospecifywhatyouwouldliketorun.Select“HelloP”.

Step8: Lookatthelogsthatweregeneratedafterrunningtheprogram.Itdoesn’tlook
likemuch.Youshouldbeseeingsomethinglikethis;

While
thisnot
seem
like
anything significant, the logs have signalled that the program ran correctly. This is
excellent!However,manyuserswillprefertoseeavisualrepresentationoftheirprogram.
Here’sasimplewaytodoso;

Step9: Click your start button. Use the search function (or manually navigate) to the
“Python(commandline)”program.





Step10: Oncethecommandpromptopens,typethesamelineofcodefromstep5into

thecommandprompt.Youshouldseethefollowing:





Asyoucansee,thecommandwasexecutedwithinthecommandprompt.

Thisgivesyouagoodoverviewofhowtogoaboutcreatingaprojectandwatchingitrun.
Unlike other programming languages, Python doesn’t need or utilize a graphical user
interfacewhenrunningaprogram.Thiscanbeconfusingforthosethatarecomingover
fromothervisualprogramminglanguages,butultimatelydoesn’teffectmuch.


Summary

Herearethepointsthatwerecoveredinthischapter:



WhatisanIDE
WhatdoesanIDEconsistof
HowtomakeasampleprogramwithPython
ThebasicsofprogrammingwithPython




Chapter3:BuildingOurFirstPrograms
“Now,it’smybeliefthatPythonisaloteasierthantoteachtostudentsprogrammingand

teachthemCorC++orJavaatthesametimebecauseallthedetailsofthelanguagesare
somuchharder.Otherscriptinglanguagesreallydon’tworkverywellthereeither .”GuidovanRossam

Inthischapteryouwilllearn:

Whatareindentations
ThebasicsofPythonProgramming
ThecomponentsofPythonProgramming
Basiccoding


NowthatwehaveseenPythoninaction,it’stimetodiveinheadfirst.Beforecodingour
own program, there are a few things that need to be understood about the language to
maketheearlylearningprocessgoasseamlesslyaspossible.



Indentation
Oneofthefirstcaveatsthatexperiencedprogrammersrunintowhenmakingthe
switch to Python is the fact that the language does not use braces to indicate blocks of
code–insteadallblocksofcodearedenotedbyindentation.Thisindentationisastrict
functionofthelanguage.Ifyouindentthewrongnumberofspaces–theprogramwon’t
runcorrectly.So,youneedtobecarefulwhenmakingcodes.Usingcommentstohelpyou
spotacodecanhelpidentifyacode.


In Python, the number of spaces for indentations is variable. However, all of the
statementswithinasingleblockofcodehavetobeintendedthesameamount.Todrive
thispointhome,thefollowingcodewouldrunfine;


ifTrue:
print “ True ”
else:
print “ False ”

Notice that both “print” statements are indented different amounts. This is fine, because
theyaretwoseparateblocksofcode.Here’sanexampleofincorrectlyindentedcode;

ifTrue:
print “ Answer ”
print “ True ”
else:
print “ Answer ”
print “ False ”

Thisblockofcodewon’trunproperly.Both“print”commandsinsidethe“else”statement
belong to one block of code, but are not indented the same amount. This causes the
interpretertoregard“print“False””asifitwereit’sownstatement,outsideofthe“else”
statement’sinfluence.



Variables

Variables,ineveryprogramminglanguage,arememorylocationsthatstorevaluesandso,
everytimeyoucreateavariable,youalsoreservememoryforthatparticularvariable.
Unlikesomeotherprogramminglanguages,youneednotdeclareavariableexplicitlyin
Python.Allyouneedtodoistousetheequalto(=)signtoassignavaluetoavariable.
Here’sanexample:


age=29
city=X
name=Ron

printage
printcity
printname


×