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

Python academy the stress free way to learning python inside and out

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.25 MB, 164 trang )


PythonAcademy



TheStressFreeWayToLearningPythonInside&Out


TableofContents
PythonAcademy
TheStressFreeWayToLearningPythonInside&Out
Introduction
Iwanttothankyouandcongratulateyoufordownloadingthebook,“LearntheBasicsofPythonProgrammingin
2Weeks”.
Chapter1:IntroductiontoPython
Chapter2:Syntax
Identifiers
BlankLines
Chapter3:DataTypes
Chapter4:Operators
ArithmeticOperators
ComparisonOperatorsorRelationalOperators
AssignmentOperators
BitwiseOperators
LogicalOperators
MembershipOperators
IdentityOperators
Conclusion


Introduction


Chapter1:What’sNew?
WINDOWS10BOOTCAMP
LearntheBasicsofWindows10in2Weeks!
MoreFreeandBargainBooksatKindleBookSpot.com
Introduction
Part1:FirstWeek
Chapter1:InstallingWindows10
Chapter2:UsingtheStartMenu
Chapter3:UnderstandingSettings
Chapter4:UnderstandingInterface
Part2:SecondWeek
Chapter5:UnderstandingtheFeatures
Chapter6:KeyboardShortcutsandMoreTricks
Chapter7:FAQs
WordpressBootcamp
LearntheBasicsofWordpressinTwoWeeks
TableofContents
Introduction
Chapter1–WhyLearnWordPress?
Chapter2–FirstWeek:Setup,Dashboard,AdminBar,Settings,LinksandImages


Chapter3–SecondWeek
SEOBootcamp
LearntheBasicsofSEOin2Weeks
TableOfContents
Introduction
Chapter1:WhatisSEOandWhyisitImportanttoyourWebsite?
Chapter2:Limitationsofthesearchtechnology
Chapter3:YourTargetUsers:TheBeginningofyourSearchMarketingStrategy

Chapter4:ChoosingKeywordstoRank
Chapter5:UserExperienceAffectsyourRanking
Chapter6:BuildingyourWebpages’LinkProfile
Conclusion
Bonus:ClaimYourFreeBonusBooksNow!




Introduction



I want to thank you and congratulate you for downloading the book, “ Learn the

BasicsofPythonProgrammingin2Weeks ” .



This book contains proven steps and strategies on how to write and run programs in
Python.Therearesamplecodesandprogramsthatyoucanuseasguidelines.

This book also contains an introduction to the programming language, including a brief
history and the fundamentals of Python. It also contains detailed explanations about the
featuresfoundinPython.

Thanksagainfordownloadingthisbook,Ihopeyouenjoyit!

Bonus:AsathankyouI’dliketoofferyouagift.I’ve
includedafewbonusbooks.Checkoutthetableofcontents

orgototheverybotomtofindoutmore!



©Copyright2014by______________________-Allrightsreserved.

Thisdocumentisgearedtowardsprovidingexactandreliableinformationinregardstothe
topic and issue covered. The publication is sold with the idea that the publisher is not
required to render accounting, officially permitted, or otherwise, qualified services. 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.

Innowayisitlegaltoreproduce,duplicate,ortransmitanypartofthisdocumentineither
electronicmeansorinprintedformat.Recordingofthispublicationisstrictlyprohibited
andanystorageofthisdocumentisnotallowedunlesswithwrittenpermissionfromthe
publisher.Allrightsreserved.

Theinformationprovidedhereinisstatedtobetruthfulandconsistent,inthatanyliability,
intermsofinattentionorotherwise,byanyusageorabuseofanypolicies,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.

Theinformationhereinisofferedforinformationalpurposessolely,andisuniversalasso.
Thepresentationoftheinformationiswithoutcontractoranytypeofguaranteeassurance.

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.


Chapter1:IntroductiontoPython


If you are looking for a general purpose, high level programming language with code
readabilityasitsmainfocalpoint,youshouldconsiderPython.Ithasasyntaxthatallows
you to express concepts using fewer lines of code than other programming languages,
suchasC,C++,andJava.Itsupportsawiderangeofprogrammingparadigms,thereby
encompassingimperative,functionalandobject-orientedprogramming.Also,itfeaturesa
comprehensive standard library, a dynamic tape system and an automatic memory
management.
Thereareplentyofinterpretersyoucanuseforinstallationondifferentoperatingsystems;
hence,itispossibleforyoutoexecutePythononvarioussystems.Youcanevenmakeuse
ofthird-partyapplications.Ifyoudonotwanttoinstallaninterpreter,youcanpackagethe
code into standalone executable programs so that you can effectively distribute Pythonbasedsoftwaretodifferentenvironments.

ABriefHistoryofthePythonProgrammingLanguage
Python was developed by Guido van Rossum in the late 1980 ’ s. It was initially just a
Christmasproject.VanRossumwantedaninterpreterforascriptinglanguagethatCand
UNIX hackers will use. His little project eventually upgraded to Python 2.0, which was

released on October 2000. This new version had a complete garbage collector and
Unicode support. Python 3.0, also called Python 3000 and py3k, was released in
December2008andhadfeaturesthatwerebackportedtoversions2.6and2.7.
WhyshouldyouUsePython?


Programminglanguagesexistforareason.Python,forinstance,wasdevelopedtoallow
programmers to create efficient and productive codes. Its main objective is to help
beginnerslearnaprogramminglanguageeasilyandquickly.Duetothislesslearningtime,
youcancreatemoreusefulapplicationsthatwillbedifficulttodowithmoreobscureand
complicatedprogramminglanguages.
WithPython,youcanalsobenefitfromlessdevelopmenttimewhencodingapplications.
Asmentionedearlier,PythonhasfewerlinesofcodethanC,C++,andJava.Itscodesare
actuallyfivetotentimesshorter;thus,makingitmoreefficientandlesscomplicated.You
gettospendlesstimeindevelopingapplicationsandmoretimetweakingandimproving
them.
Whenitcomestocheckingforbugsanderrors,itiscrucialfortheprogramminglanguage
that you use to be easy to read and comprehend. If the programming language is too
complicated,youmayhaveahardtimecodingandcheckingyourprogram.WithPython,
codes are much easier to read and write; hence, you can easily interpret the codes and
makethenecessarychanges.
Furthermore, Python has many other uses. It is ideal for scripting applications that are
browser-based,creatinggreatuserinterfacesandroughapplicationexamples,interacting
withdatabases,workingwithXMLanddesigningmathematic,engineeringandscientific
applications.

Pythonvs.C#,Java,andPerl
Youmayfindcomparingprogramminglanguageswithoneanothertobeasubjectivetask.
Usually,theirdifferencesareamatterofpersonalpreference.Nonetheless,therearetimes
when such comparisons are backed up by scientific data. Anyway, you have to keep in

mindthatanall-encompassingprogramminglanguagedoesnotexist.Asaprogrammer,


youjusthavetofindonethatworksbestforyourgoalsorneeds.
C#
If you have a background in Java, you may notice that C# and Java are highly similar.
Then again, C# still has its own advantages and disadvantages compared to Java.
Microsoft claims that their primary objective in developing C# is to produce a better
version of C and C++. Compared to C#, however, Python has better scientific and
engineering applications and better multiplatform support. It is more extendable when it
comestousingC,C++andJava.Itiseasiertolearnandcomprehend,anditallowsthe
useofvariouscomputerenvironments.Italsohasmoreconcisecodes.
Java
Programmers consider Java as a one-stop shop programming language. For many years,
they have searched for something that can be run and written anywhere and they found
Java,whichcanperformwellindifferentplatformsandcomputerenvironments.Withthis
being said, Python is also a one-stop shop programming language. It is very similar to
Java,exceptthatithasmoreconcisecodesanditiseasiertolearnandcomprehend.Itis
muchfastertodevelopandithasimproveddataboxesorvariablesthatcanstoredifferent
datatypesthatareusefulwhenrunningapplications.
PERL
PERLstandsforPracticalExtractionandReportLanguage.Itisaprogramminglanguage
that is suitable for acquiring and processing data from another database. In comparison,
PythonisbetterthanPERLbecauseitiseasiertoread,implement,learnandunderstand.It
hasbetterJavaintegrationanddataprotection.Italsohaslessplatform-specificbiases.
WhyPythonisIdealforBeginners?
If you have just started programming, you may want to consider Python. It is ideal for


beginners because it has a consistent and simple syntax and vast standard library that

allowsyoutodomultipleprojects.Theassignmentsinvolvedarenotlimitedtotheusual
four-functioncalculatorandcheckbalancingprograms.
AsyougetusedtowritingprogramsinPython,youwillrealizethatitisactuallyeasyto
makerealisticapplications.Theinteractiveinterpreterwillalsoallowyoutotestlanguage
features. In Python, you can concentrate on essential programming skills, such as
programming decomposition and data type design, and fundamental concepts, including
proceduresandloops.
Since Python involves the use of multiple libraries and system calls, you can develop
applications with interfaces that are easy to program. You can also complete tasks
necessaryfortheapplicationprogramminginterface(API).
Do not worry if you have never used any other programming language before. Even
people with no prior programming knowledge or experience can easily grasp the
fundamentalsofthePythonprogramminglanguage.
As for the installation, Python is easy to install. Most UNIX and Linux distributions
actuallyincludeitintheirpackage.IfyoupurchaseaWindowscomputerfromHewlettPackard(HP),youcanreadilyusePythonasitcomespre-installedwiththesystem.
Tomakethingseasierforyou,youshouldstudyhowtousethetexteditorsaswellasthe
integrateddevelopmentenvironments(IDEs).Itwillalsobehelpfultoreadprogramming
bookswithsamplecodesandprograms.
Regarding copyright, the developers of Python allow programmers to do whatever they
want with the source, as long as they do not forget to include the copyrights. The
copyrightrulesarenotthatstrict.Youcanevensellcopiesinbinaryandsourceform,as
wellasproductsinvolvingPythonuse.However,ifyouwishtousethelogo,seetoitthat
youobtainpermission.


Pythonishighlystable.Infact,itisstableenoughforregularuse.Youcanexpectanew
versionwithinsixtoeighteenmonths.Thedevelopersissuebugfixreleasestoensurethat
thenewerversionsarebetterthanthepreviousones.
If you want to perform a static analysis or search for bugs, you can use Pylint or
PyChecker.Thepreviousisatoolthatchecksthemoduletoseeifitabidesbythecoding

standardaswellasallowthecustomizationofplug-ins.Thelatterisastaticanalysistool
thatfindsbugsinthesourcecode.
Sonowthatyouhavelearnedaboutthefundamentalsoftheprogramminglanguage,you
may still wonder how Python got its name. Was Guido van Rossum fond of pythons?
Well,hewasactuallyfondofthetelevisionshowcalledMontyPython ’ sFlyingCircus,
notthereptile.
DuringthetimeofPython ’ sdevelopment,hewasreadingscriptsfromthecomedyseries
andthoughtthat ‘ Python ’willbeasuitablenamesinceitwasshort,uniqueandhasthe
rightamountofmystery.Infact,referencestothecomedyshowareallowedandactually
encouragedindocumentations.



Chapter2:Syntax

Pythonhasasimpleandstraightforwardsyntax.Itevenencouragesprogrammerstowrite
programswithoutusingpreparedorboilerplatecodes.Theprintdirectiveisactuallythe
simplestofalldirectives.Itprintsoutlinesandincludesnewlines.Youmaynoticethatthe
printdirectiveisdifferentinthenewmajorversionsoftheprogramminglanguage.
Python2.0isthemorecommonversionwhilePython3.0supportsthelatestfeaturesand
ismoresemanticallycorrect.Anyway,theprintstatementisnotconsideredasafunction
inversion2.0;hence,youcaninvokeitwithoutincludingparenthesesinyourcode.On
theotherhand,theprintstatementisconsideredasafunctioninversion3.0;hence,you
havetouseparenthesesifyouwishtoinvokeit.

InteractiveModeProgramming
Youcanexecuteyourprogramsindifferentmodes.Ifyouinvoketheinterpreterwithout
passingthescriptfileasaparameter,thisiswhatyouwillget:
$python
Python2.4.3(#1,Nov112010,13:34:43)

[GCC4.1.220080704(RedHat4.1.2 –48)]onlinux2
Type “ help ” , “ copyright ” , “ credits ”or “ license ”formoreinformation.
>>>



When you see this prompt, you can type in your desired text then press Enter. In this
example,wewillbeusingthewords ‘ MontyPythonandtheHolyGrail ’ .
>>>print “ MontyPythonandtheHolyGrail ”;
Takenotethatifyouareusinganewerversionoftheprogramminglanguage,youneedto
useopeningandclosingparentheseswithyourprintstatement,suchasinthefollowing:
>>print( “ MontyPythonandtheHolyGrail ”);
Regardlessofwhichversionyouareusing,ifyourunthesamplecodeshownabove,you
willgetthefollowingoutput:
MontyPythonandtheHolyGrail

ScriptModeProgramming
If you invoke the interpreter with a script parameter, the script will start to execute and
continuetorununtilitisdone.Whenitisdone,theinterpreterwillnotbeactiveanymore.
Considerthefollowingexample.Thesampleprogramiswritteninascriptandhasa.py
extension:
print “ MontyPython ’ sFlyingCircus ” ;
Ifyoutypeintheabovegivensourcecodeinatest.pyfileandrunitas
$pythontest.py
youwillobtainthefollowingoutput:
MontyPython ’ sFlyingCircus
Anotherwaytoexecutescriptsistomodifythe.pyfile,suchas:
#!/usr/bin/python



print “ MontyPython ’ sFlyingCircus ” ;

Ifyourunitas

$chmod+xtest.py
$./test.py

yougetthefollowingoutput:

MontyPython ’ sFlyingCircus



Identifiers
Anidentifierisbasicallyusedtodeterminefunctions,variables,modules,classes,andany
otherobjects.Itbeginswithanunderscore(_)oraletter.Itisthenfollowedbydigits,
underscores,zeroorotherletters.Asaprogrammer,feelfreetouseanyletterordigit.You
canuseuppercaseandlowercaseletters.
However,youcannotusepunctuationsandspecialcharacters,suchas@,$,and%,within
theidentifiers.Inaddition,Pythonisacasesensitiveprogramminglanguage.Thismeans
thatyouhavetobecarefulwhenyouuseuppercaseandlowercaselettersinyourcodes.
Forinstance,wendy,Wendy,andWENDYareallthesamenameandyettheyareregarded
asthreedifferentidentifiersinPython.
RulesforIdentifiersinPython
ThereareseveralrulesthatyouhavetoabidebywhenwritingprogramsinPython:
Theclassnamemustalwaysstartwithanuppercasecharacterwhiletherestofthe
identifiersmuststartwithalowercasecharacter.
Theidentifierisprivateifitstartswithjustoneleadingunderscore.
Theidentifierisstronglyprivateifitstartswithtwoleadingunderscores.
The identifier is a language-defined special name if it ends with two trailing

underscores.



ReservedWords
Take note that there are certain words you cannot use as constants, identifier names, or
variablesinPython.Allkeywordsarealsowrittenusinglowercaseletters.Thefollowing
isatableofthereservedwordsintheprogramminglanguage:

And

Assert Break Class Continue

def

del

exec

finally for

from global

if

import in

is

Not


or

print raise

return try


elif

pass

else

except

lambda

while with yield


IndentationandLines
Therearenobracesfortheindicationofblocksofcodeforclassdefinitionandfunctionin
Python.Likewise,flowcontrolisnotincluded.Ifyouwanttodenotesuchblocksofcode,
youhavetomakeuseoflineindentation.Youcanadjustitforspaces,butmakesureto
indentallstatementswithablock,too.Tohelpyouunderstandthisfurther,considerthe
followingsamplecodes:
ifTrue:
print “ Correct ”
else:

print “ Incorrect ”

ifTrue
print “ Input ”
print “ Correct ”
else:
print “ Input ”
print “ False

Runningthefirstgivenexamplegeneratesanoutput.Runningthesecondone,however,
resultsinanerror.Whydidthishappen?Well,youhavetokeepinmindthatinPython,
blocksareformedbyindentingcontinuouslineswiththesameamountofspace.
Indentation is simply a way to group statements. Programmers use it in place of curly


bracesofblocksofcode.Tabsandspacesaresupported,butstandardindentationrequires
standardcodestohavesimilaramountsofspaces.Ingeneral,fourspacesareused.Takea
lookatthefollowingexample:
w=1
ifw==1:
#Thisshowsanindentationwithexactlyfourspaces
print “wis1. “



IndentationMyths
TherearecertainmythsthatsurroundindentationinPython.Herearesomeofthem:
Awhitespaceisnecessaryineverysourcecode.

Actually, you do not have to use whitespaces in all your source codes. A

whitespaceisnotnecessarilysignificant,althoughanindentationis.Asyouhave
learned, this is the whitespace found at the very left part of a statement.
Everywhereelse,awhitespaceisnotthatsignificantandmaybeomitted.Youcan
useitinanywayyoulike,eveninsertingarbitrarywhitespacesoremptylinesthat
donotcontainanythinganywhereinyourprogram.

Moreover,theexactamountofindentationdoesnotreallymatter,buttherelative
indentation of your nested blocks does. The indentation level is actually not
recognizedwhenyouuseimplicitorexplicitcontinuationlines.Forinstance,you
maysplitalistacrossmultiplelines.Theindentationisjustnotsignificantatall.
Takealookatthefollowingexample:

foo=[
‘astring‘,
‘anotherstring‘,
‘ashortstring‘
]
printfoo



Ifyouruntheabovegivencode,youwillgetthefollowingoutput:

[‘astring‘,‘anotherstring‘,‘ashortstring‘]


Hereisanotherexample:

bar=‘lookatthisexample‘\
‘ofalongstring‘\

‘thatissplit‘\
‘acrossmultiplelines‘
printbar

Ifyouruntheabovegivencode,youwillobtainthefollowingoutput:

lookatthisexampleofalongstringthatissplitacrossmultiplelines

Acertainstyleofindentationshouldbeusedinyourprograms.

Well,thisoneisbothtrueanduntrue.Youcanwritetheinnerblockonalineand


notindentit.Youcanuseanyofthefollowingversionsofthe“ifstatement”since
allofthemarevalidandproducethesameoutput:

if1+1==2:
print“foo”
print“bar”
w=99

if1+1==2:
print“foo”;print“bar“;w=99

if1+1==2:print“foo“;print“bar“;w=99

Asaprogrammer,youmaywishtowriteyourblockofcodeinseparatelines,such
as the one shown in the first example. However, there are times when there are
similarifstatementsthatyoucanconvenientlywriteoneachline.


Incaseyoudecidetowriteyourblockofcodeonseparatelines,thenyouhaveto
followtherulesofindentation.Youhavetoindenttheenclosedblockmorethan
the“ifstatement”.

Inconclusion,youwillbeforcedtoabidebythisruleinPython,unlessyouopted


×