




下載本文檔
版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
IntroductiontoProgrammingwithVivianCopyright?2015bySoftwareDevelopment歡迎加Python歡迎加Python編程學習交,群里免費提供500+本Python書籍 .ThisbookcontainsmaterialprotectedunderInternationalandFederalCopyrightLawsandTreaties.Anyunauthorizedreprintoruseofthismaterialisprohibited.Nopartofthisbookmaybereproducedortransmittedinanyformorbyanymeans,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorageandretrievalsystemwithoutexpresswrittenpermissionfromtheauthor/Anyunauthorizedbroadcasting;publicperformance,copyingorre-recordingwillconstituteaninfringementofcopyright.Permissiongrantedtoreproducefor alandeducationaluseonly.Commercialcopying,hiring,lendingisprohibited.Maybeusedfreeofcharge.Sellingwithoutpriorwrittenconsentprohibited.Obtainpermissionbeforeredistributing.InallcasesthisnoticemustremainFurtherLimitOfLiability/Di erOfWarranty:ThePublisherAndTheAuthorMakeNoRepresentationsOrWarrantiesWithRespectToTheAccuracyOrCompletenessOfTheContentsOfThisWorkAndSpecificallyDi AllWarranties,IncludingWithoutLimitationWarrantiesOfFitnessForAParticularPurpose.NoWarrantyMayBeCreatedOrExtendedBySalesOrPromotionalMaterials.TheAdviceAndStrategiesContainedHereinMayNotBeSuitableForEverySituation.ThisWorkIsSoldWithTheUnderstandingThatThePublisherIsNotEngagedInRenderingLegal,Accounting,OrOtherProfessionalServices.IfProfessionalAssistanceIsRequired,TheServicesOfACompetentProfessional ShouldBeSought.NeitherThePublisherNorTheAuthorShallBeLiableForDamagesArisingHerefrom.TheFactThatAnOrganizationOrWebsiteIsReferredToInThisWorkAsACitationAnd/OrAPotentialSourceOfFurtherInformationDoesNotMeanThatTheAuthorOrThePublisherEndorsesTheInformationTheOrganizationOrWebsiteMayPror mendationsItMayMake.Further,ReadersShouldBeAwareThatInternetWebsitesListedInThisWorkMayHaveChangedOrDisappearedBetweenWhenThisWorkWasWrittenAndWhenItIsRead.Everyefforthasbeenmadeinthepreparationofthisbooktoensuretheaccuracyoftheinformationpresented.However,theinformationcontainedinthisbookissoldwithoutwarranty,eitherexpressorimplied.Neithertheauthor,norLearntoCodeProductions,anditsdealersanddistributorswillbeheldliableforanydamagescausedorallegedtobecauseddirectlyorindirectlybythisbook.TableofTableofChapter1.WhyYouShouldLearnProgrammingChapter2.WhyPythonisthePerfectLanguageChapter3.GettingStarted:Pre-reqsChapter4.Variables,Expressions,Statement,StringsChapter5.FunctionsChapter6.Conditionals,FlowControl,DecisionsChapter7.IterationsChapter8.Lists,Dictionaries,TuplesChapter9.ObjectOrientedProgrammingChapter10.Classes,Objects,InheritanceChapter11.DebuggingChapter12.NextWhyThisTheadage“penismightierthansword”isbestservedbyprogramminglanguages.Youliterallytypeandcommunicatesolutionstoproblemsonacomputer,anditcomestoThisbookintroducesPython,thesimplestandcurrentlyoneofthemostpowerfulObjectOrientedProgramminglanguagesontheplanet.ThebookshowshowitissimilartolearninganewdialectofEnglish,onemeantforthecomputingdevicesyouholdinyourItwillintroduceyoutothebasicsofPythonlanguage:itsfundamentalbuildingblocks,theirsyntax,theirbasicuses,andhowtheyarerelatedtooneanotherincreatinglargerThisbookismeantfornovicesandbeginners.Hence,itusessimplereallifeexamples,offersshortcodeswithexplanations,andcontinuouslylinksbacktoearlierchaptersandbuildsonthem.Chapter1.WhyYouShouldLearnTheriseofsmartdevices,wirelessconnectivity,andincreasedusermobilityinofficesmadecomputersanintegralpartofourlifestyles.Asourrelianceonsmartdevicesandvariousappstocompleteadiverserangeofactivitiesincreases,learningtocodeisingakintolearningasecondNormally,welearnsecondlanguagestoincreaseourreach, egeographicandculturalbarriers,andtobeabletocommunicatewithpeoplefromdiversecultures.Smartdeviceshavebroughtdownbarriersacrossdifferentcultures,andhave eoneofourmosttrustedcompanions.However,wearenotabletoeffectivelycommunicateandinstructoursmartcompanionstoperformtheactionsthatwedesire.Learningtoeffectivelycommunicatewithcomputersandsmartdevices,andbeingabletoinstructthemtoperformdifferenttasksisfast ingsomethingmorethananaddedskill—itis ingpartofwhatitmeanstobehumaninofDigitalNatives.7ReasonsforLearningtoLearntoprogramandyouwillbeabletoexperiencethefollowingseven,awe-inspiringrealitiesofbeingaDigitalNative.It’stheonlytimewhenwritingcanliterallysolveTheadage“penismightierthansword”isbestservedbyprogramminglanguages.Youliterallytypeandcommunicatesolutionstoaproblemonacomputer,anditcomestoIt’samazingtorealizehowpowerfulthisformofcommunicationis.MostofsmartphoneusershavevisitedAppStoresandseenarangeofapps,eachsolvingauniqueproblemforus.Knowingaprogramminglanguagemeansthatyoucanbreakaproblemintosmallerproblemsandcreateprogramsforyourselfandothers.Somanyproblems,nomatterhowtrivialcannowberesolvedsimplybywritingthemoutinaprogramminglanguage.ProgrammingtransformsyourcomputerandsmartphoneintoaHumanslandedonthemoonrelyingoncomputingpoweratleasta1000timeslesspowerfulthanthecomputingpowerofoursmartphones.By2016,over2billionpeoplewillbeusingsmartphonesacrosstheglobe.Justimaginewhatthisprocessingpowercanbeputtousefor.ImaginewhatyoucancreateanddeveloponyourPCforusewithyoursmartphones: alizedapps,games,tools,andmore.ThepossibilitiesareProgrammingsimplifiestasksbyautomatingWeliveinaworldwhereefficiencyisthehallmarkofeverything.Nobodywantstoperformtediousandrepetitivetasksifyoucanpayforasolutionthatcanautomateit.Thisrangesfromofficetasksto alones.Bylearningtocode,youcancreatesimplescriptsthatsimplifytasks.Thinkofgeneratingmacrosin Office(ExcelandWord)orscriptsthatsimplifytasksyouhavetoperformregularlyatworke.g.creatingfoldersforprojects,completingforms,creatingshortcuts,addingmorefeaturestoexistingsoftware,etc.Itdevelopsyourability anddisciplinedInstructingcomputersrequiresthatgivethemstep-by-stepinstructionsthatlinkpre-determinedinputstoexpected es.Tocommunicatetothecomputer,youhavetowriteinanexplicitlanguage,fromproblemtosolution.Thisrequiresbreakingdownproblemsintosimplerones,andthenorganizingthemintoinputsandProgrammingteachesyoutoorganizethoughtsandbreakdownaproblemintoconstituents,identifyingexternalfactorsandtriggers,osimplerchunksofprogrammablecode.Thistrainsyourmindtothinkclearlyandsystematically,filteringoutinformationthathasnobearingsonthesolution,andfindingthesimplestsolutiontotheproblem.FuturejobswillrequiresoftwareCurrently,programmingmaybeaskilltoboastyourchancesofentryintothemarket,howeverasorganizationsfocusonincreasinginterdepartmentalcollaboration,theybegintopreferpeoplewithinter-disciplinaryskillsets.Inthelongrun,beingabletoprogram easkillneededtosurviveinthetechnologymarket.Becauseit’snothardtoIfyoucancomprehendEnglishlanguage,learningtoprogramissimplyamatteroflearningthelogicbehindprogrammingwords.Overtheyears,programminglanguages emoreintuitive,utilizingcommandsthatclearlystatetheirpurposeandhenceallowyoutonearlyconstruc tences“If-Then”,“Else”,“Print”,“Switch”,arejustthemostcommonlyusedcommandsinprogramminglanguage.Allyouhavetoslearnthegrammar,andwithpracticeyouwillbeabletowritethoseshortessaysthatidentifytheproblem,itscomponentsandinputs,andtheoutputsforeachprogramminghasgreatEarningAsyougetbetteratprogramming,youcaneasilyleverageyourproblemsolvingskillstodevelopsoftwareforsale.Thisincludesworkingasafreelancer—buildingapps,develocustomsoftware,creatinganddesigningwebsites,orhelclientscompletetasksusingexistingsoftwareandplatforms ExcelandWord,Flash,Java,InConclusion—PreparetoProgrammingisanadd-ontoyourcurrentunderstandingoftheEnglishlanguage.Thinkofitasanewdialect,onethatyourcomputerandsmartdeviceunderstands,onethathasalotofbenefitsinthemodernworld,iseasytolearnandonethatwillsoon eamusthavefordigitalnatives.Chapter2.WhyPythonisthePerfectInanagewheremachinesare inghighlyin ligentandarecontinuouslysimplifyinghuman-machineinteractions,itonlymakessensetouseanin programminglanguage.ExistingstaticallytypedlanguagessuchasPascal,C,orothersubsetsofC++andJavaintroduceverbosesyntaxthatcloudtheactualprocessofproblem positionanddesignofdatatypesthathavetobeprogrammed.Hence,forsomeonewhodoesnotknowhowtocode,theselanguagesseemunnatural.Furthermore,theadditionalcomplexityofthesyntaxonlyslowsdownthepaceofingrainingthemethodologyofprogramming.ThisiswherePythonbringsinthepowerofsimpleandconsistentsyntax,backedbyalargestandardlibrarywithrealproblems.NotwithstandingtheriseinitspopularityinAmericancollegesasreportedbytheAssociationforComputingMachinery,PythonhaseffectivelyreplacedJavaasthefirstlanguageofchoiceforbuddingprogrammers.SowhatismakingPythontheperfectlanguageaftertwodecadesofbeinginthe#1—MinimalInstallingandrunningPythonisextremelysimple.Allyouhaveto sdownloadthefileandeitherrunitthroughtheTerminalprogram(forMac),orthePowerSprogram(Windows),andLoandbehold!You’rerunningPython.#2—WritingaprogramisakintowritinginPythonisauniversallanguage.Thismeansthatitssyntaxandcodinglingoisexceptionallysimplifiedandeasy.PythonistheclosestthingtowritingalogicalargumentinEnglish.Thecommandsaresimpleandtheadditionalbaggageofgrammar(programmingsyntaxsuchasbrackets,colons,quotes,etc)isminimal.Yougrasphowtosystematicallybreakdownaproblemintosimplersteps,andyoucaneasilycodeitinPython.Inaphrase:agreatfirstexperienceforanyThestandardfirsthands-onprogrammingexperiencethatallbeginnersgothroughistoprintsomethingonthescreenusingcoding.Thisisnormallythewords“oWorld”,amongothers.Pythonmakesitliterallyamatterofwritingao Comparethistothefollowing publicstaticvoidmain(String[]args) o, Furthermore,whenyoumoveaheadintothecourse,otherexamplesofsimplifiedprogrammingwillleapout,includingsimplereading/writingofinformation,stringprocessing,GUI’s,websitecode,Databases,websites,etc.Itssimplicityandeaseofprogrammingisthereasonwhyithasbeenadoptedbysomanypeopleandforsuchawiderangeoftasks.Thisisfurthermadeenjoyablebythefactthataverylargecommunityofenthusiasticdevelopersisalwaysabuzztoaidnewcomerseinitiatedintothe#3—PythoniseasytoPythonisdesignedtobeaneasy“Readability”ofacodemayandseemunimportantrightnow,butit esthedefiningfactorwhenthecode eslargerandmorecomplex.Readabilityisveryimportant,becauseunlikeacoursebook,thechapters(orchunksofcode)arenotalwaysarrangedtoworkinastep-by-steporlinearorder.Attimescodingblocksinthefarrecessesofthecodeneedtobecalledearlier,orlater,multipletimesthroughoutthecode,andsoon.Easeofreadabilityisimportantforsharingacodebetweenateam,fortroubleshootingaprogram,andformakingchangestoit.Intraditionallanguages,reading increasinglydifficultasbecauseofallthenon-Englishgrammaticalsyntax.Pythonusesindentationtogivestructuretothecode,andthoughprogrammerswhoaremigratingfromadifferentlanguagetoPythonmaybeheardcomplainingaboutthelack(andnearabsence)ofbraces,itisoneofthekeybenefitsofPython:itsimplyde-clutterstheworkenvironment!Thinkofindentationsliketheheadingsinyourwordprocessingsoftware(H1,H2,H3,H4,H5,andsoon).Incodingtheheadingsarenormallycurlybrackets(“{}”)thathavetobeaddedatthestartandendoftheparagraph.Asaresult,twotypesofcommunicationarehappeningsimultaneously:bracestolthemachineabouttheprogram,andtheindentationstolthereader(anotherprogrammer)whattheprogramisabout.NowimagineNOThavingtoaddbracketsandindentationandfollowalegendyouhavecreatedearliertokeepyourprogramreadable.Pythondoesthisbyofferingasinglestructuretodenoteaprogram:makingiteasierforhumansandcomputersaliketoreaditwithease.#4—YoudonothavetocompiletheprogramtorunWhenyou’relearningsomethingnew,mistakesareboundtohappen.Howthosemistakesareshowntoyouoftenplaysacrucialroleinhowmotivatedyouaretotryagain,orhowaffectedyouarebythemistakethatyouhavemade.WithPython,allerrorsareidentifiedatruntimeinsteadofshowingafailuretocompileerror.Thismakesiteasiertoidentifyandfixmistakesimmedia Thisisincrediblyusefulwhenyouwillbedesigningacomplexalgorithmwherechangesaremadecontinuously.Whereotherprogramminglanguageswillwastetimetakingyouthroughthecompile-run-debugcycle,Pythonsimplyshowstheresult(ortheproblem)inthesameinterpreter.Hence,youcanmakeinnumerablechangestoapieceofcodeandexecuteitinreal-timeintheinterpreter.Thisbooststhelearningprocessasyoucanconsciouslymakeerrors,seeitsimpact,andtroubleshoottheprogram.Thisdramaticallyreducesthedevelopmentcycle, esespeciallyusefulforrapidprototyofyourcode.#5—PythonisPythonisanopenontwoOpensourceasprogrammingBuiltusingOpenAsanopensourceplatform,itsliberaldistributionlicenseallowsthelanguagetobeusedforcodingprograms/appsthatcanseamlesslybeintegratedasanextensionofotherproprietylanguages.Intermsofcodingarchitecture,Pythonisgreatatintrospectionbecausethecodeisbasedondiscretechunksofprograms(knownasobjects).Wewillgettechnicallater,butforthemoment“beingopen”meansthatitwillbereallyhardforyoutowritedirtycodeorsidesteppropercodingmethodstosolveproblems.Hence,Pythonforcesyoutowritebettercodefromthebeginning,andthisprovesveryhelpfulduringdebugging.歡迎加Python編程歡迎加Python編程學習交,群里免費提供500+本Python書籍Chapter3.GettingStarted:Pre-ThereareonlytwoprerequisitesforgettingstartedwithinstallingandusingPython:Reasonableknowledgeofusingacomputerandinternet.Acompellingdesireforlearninganewlanguageforcommunicatingwith歡迎加Python歡迎加Python編程學習交,群里免費提供500+本Python書籍InstallingPythononDownloadthelatestversionofPythonfromtheofficialWebsite.NOTE:NOTE:Twoversionsofthelanguageareavailable,Python2.xandPython3.xThedifference,inallitssimplicityisthatPython2.xislegacyi.e.itistheonethathasbeeninstalledonmostdevicesandhenceisthecurrentnormforPython,whereas,Python3.xisthepresentandfutureofthelanguage.TheWindowsversionisdownloadedasanMkage,andcanbeinstalledwithadouble-clickontheopensfile.AllowthewizardtoinstallPythontothedefauForPython3.xitwillbeC:\Python3x\—(xbeingreplacedbytheversionyou’vedownloaded,thelatestbeing2.7)NOTENOTE:ThedifferentfoldersmeanthatyoucaninstallmultipleversionsofPythononthesamesystemwithoutcausingany However,asingleinterpreteractsasthedefaultapplicationforPythonfiletypes. That’sit.YoucanusePython;however,itis mendedthatyouinstallthelibrariesandtoolsdescribednextbeforeworkingonwritingyourcode.Inparticular,Setuptoolsisamustinstallasitallowsyoutoeasilyuseotherthird-partyPythonlibraries.Setuptools+FromalltheSetuptools,thisisthemostcrucialthird-partyPythonsoftwarebecauseitextendsthecapabilitiesofthepackagingandinstallationfacilities(offeredinthedistutilspresentinthestandardlibrary).OncetheSetuptoolsisaddedtoyourPythonsystemanddirectory,allPythoncompliantthird-partysoftwarecanbeaddedusingasinglecommand.Furthermore,withtheSetuptoolsinstalled,youcanaddanetworkinstallationcapabilitytothesoftwarethatyouPython3,generally,comesequippedwithPIP.YoucandownloadthelatestversionoftheSetuptoolsforWindowsHERE.NowinstallPIP,areplacementforthePythoncommandeasy_installandwhichintroducesun-installationofdifferentpackages.VirtualNext,youhavetoinstallaVirtualEnvironment,virtualenv,atooltokeepeach歡迎加入非Python編程學習交 ,群里免費提供500+本Python書籍self-containedandseparatefromoneanother.Thinkofitthisway:whenyouwriteacode,itleveragesthePythonworkenvironmenttoreduceitssize(e.g.usingsomepre-madefunctionsfromthePythonlibrary).Hence,whenitissaved,onlytheessentialinformationneededforthesavedfiletobereopenedandruninthePythonworkenvironment.NowyoucreateanothercodeandsaveNowthenewprojectmayusedifferentlibraryobjectsfromPython,however,unlessamechanismexiststokeeptheirrelianceseparatefromoneanother,oneprogramcaneasilywiththeAvirtualenvironmentseparatesalldependenciesrequiredbydifferentprojectsinseparateplaces.Hence,eachprogramcansafelyruninitsownsafehaven.DownloaditfromThesecondAstrongdesiretolearnhowtowritecomputerIfyoudon’tknowhowtoprogramandarenewofPython,thenunderstandthataswithanynewlanguage,ittakestime,practice,andperseveranceinfaceofmistakesandsmallfailures.Hence,youmusthaveastrongdesiretolearnthelanguagetosucceed.StrongdesiretoPythonrequiresfocusedeffortinlearningthebasics,learninganewmethodforlogicallybreakingdownaproblemintoconstituentparts,learninganewprogrammingmethodology(Pythonisanobjectorientedprogramminglanguage),andpracticingcodingbehaviorinanewcodingenvironment.Don’texpectamiracletoYouwon’tlearnitbysimply ofthisAswithanylanguage(spokenorcoded),practiceandexperiencematteralot.Simplyreadingandmemorizingsyntaxwillnotbringamiraculoustransformationandmakeyouanaptprogrammerinthefield.Unlessyouarewilledbyatruedesiretolearnthenewlanguage,learningtoprogramcaneboring,mistakeswillcompoundasade-motivatingfactor,andyouwillnotingraina yticprocessofbreakingdownproblemsandwritingPractice,morepractice,andevenmoreAlllanguagesarelearnedbyrepetitionandYouhavetolearnhowtoputtogetherphrasesandcreatemeaningfulsentencesoutofthem.WithPython,itisaboutusingthesyntaxandcommandstocreatechunksofcodethatcanperformanaction(takeinput,compute,displayanoutput,etc.),anddosoThisbookwillofferyouthebasicsofthelanguage,butyoumustwillyourselftoputyourbraininhighgearandwriteALOTofcodefordifferentproblems.Onlythenwilltheinformationthatissharedinthisbookwillstickwithyou.Thinkofthethingsyouhave egoodatovertheyears:talking,surfing,gaming,playingmusic,generalknowledgeaboutfashion,writinggoodessays,humor,andmore.Allofthemneededtobepracticedagainandagaintogainsufficientcommandandconfidenceinyouabilities.ProgrammingwithPythonisquitesimilartothatChapter4.Variables,Expressions,Statement,RememberthoseEnglishgrammarlessons?How“eachsentence”ismadeofasubjectandanobject,hasnouns,pronouns,auxiliaryverbs,andadjectives,andthelike?Justrememberhowwordsandauxiliaryverbswereusedtocreatesentences,andhowthesesentencesareusedtocommunicatemorecomplexthoughts.ThisiswhatwearegoingtodoPython(andmostotherprogramminglanguages)aremadeofsomeuniversalbasiccomponents.Theseinclude(inorderofincreasingcomplexity)variables,expressions,statements,andstrings.Thenamesareself-explanatory.Let’sseetheminAvariableisthe“x”youtriedtofindinmostofyourmathclasses.InprogrammingitisdatatypecapableofcontainingchangeableTheabilitytomanipulatevariableinaprogramminglanguageisoneofthemostpowerfulfeaturesinthecodingworld.Hence,wemustbeginbyunderstanding“values”inValuesanddataValuesarecategorizedaccordingtothetypeofdatatheycanhandle.Forexample,“o,Programming!”,“2”,and“2.3”areallconsideredvaluesinPython,excepteachbelongstoadifferentcategoryordifferentdatatype.NOTE:NOTE:Datatypedonatesthedifferenttypesofdatathatcanbeusede.g.characters,numbers,floatpoint(decimalnumbers),etc.Thenumeric2isanintegerbecauseitcontainsawholenumber,whereasthe“ Programming!”isastringbecauseitcontainsastringofletters,and“2.3”isafloatbecauseithasdecimalnumber.YourPythoninterpreterisabletoidentifyandusestringsasasinglevalueenclosedwithinthequotationmarks.Ifinconfusionaboutthetype,let lyouthedatatypeofyourvaluewiththe()>>>>>>type o, <type >>>type <type Notethatthestringsarealwayscontainedwithinquotes“”.Hence,ifyouweretoputnumericvalueswithinthesequotes,theyautomatically estrings.>>>type <type Furthermore,whenwritingstrings,avoidusingcommastoseparatetens,hundreds,andthousands.Forexample,ifyouwanttowritetwohundredthousandas2,00,000,Pythonwouldreafollows:>>>print(2,000,000) 20 UnexpectedThat’sbecausecommasareinterpretedbyPythonasseparators.Hence,youseethreevalues:2,0,and0.NOTE:NOTE:Thesyntaxforprintisprint(x)with‘x’beingreplacedbystrings(“string”)ornormalnumericvalue(2)ThisThisisdifferentfromPython2,wherethesyntaxissimply:printx,print2,orprintOthertypesincludefloat(fordecimal>>>type<type>>>type<typeNOTE:NOTE:Youcanuseboth,single(‘’)anddouble(“”)quotesforwritingstringsinPython.AND,youcanusedoublequoteswithinsinglequotes.Forexample:(‘Hesaid,“Loandbehold!”‘)Let’sstartwithRememberhowbasicequationswerecreatedinQuestion:IfSamboughttwoeBooksfor$3,howmuchwillitcosttopurchase5eBooks?Wenormallybeganwithsupposing“x”asthecostof5eBooks.Oncesupposed,“x”canbeusedanywhereinthesolutionandanyonecaneasilyfigure(interpret)that“x”isreferringtothe“Costof5eBooks”definedinthebeginning.Inprogramming,avariableisthenamethatreferstoachangeablevalue—onethatcanbechangedandautomaticallyupdatedatwill.Likemath,variableshavetobedeclared/created(supposed)andthenassignedavalue.Inpython,thevalueofavariableisassignedusingtheassignmentstatement:>>>message>>>message=“I’mprogrammingwith>>>x=>>>yr=Noticehoweachtypeofdataisassignedinasimilarmanner,startingwithastring,aninteger,andafloatingpointnumber.Themostimportantthingistheequalsign“=”thatseparatesthenameofthevariable(lefthandside)fromthevalueofthevariable(righthandside).Theequalsign“=”isknownastheassignmentoperator.Theleft-hand,right-handdivideisarule.Deviationisnotpermitted.Ifyoureversetheorder,it esmeaninglessfortheinterpreter.Hence,thefollowingmakesno>>>“I’m>>>“I’mprogrammingwithPython!”=>>>2015=>>>365.25=TypesofVariablesalsohavetypes.Intheexampleabove,themessageisastring,‘x’isaninteger,and‘yr’isafloat.Youcanverifythetypeofthevariableusing>>><type>>>>>><type>>><type>>><typeNotehowthetypeofthevariablecorrespondstothetypeofthevalueitNamingYourVariables,TheCertainnamingconventionsareusedwhennamingvariables.Thesearesimplystandardsthatareusedtostandardizehowcodeiswrittenandtokeepitclean.Thisgainsimportanceasyourcodegetslongerandyourvariables emoredescriptive.Additionally,certainpythonruleslimithowyourvariablecanbeassigned.YourvariableAlwaysbegin Neveruseillegalcharacters($,&,*,NeveruseaPythonTherefore,thefollowingwillresultinsyntax>>>14numbers=“What>>>14numbers=“WhatarethosefourteenSyntaxError:invalid>>>Increase$=SyntaxError:invalid>>>class=“PythonBasicsSyntaxError:invalidNow“class”isaPythonkeyword,whi eansitispartofitsrulesandstructure.Pythonhasthirty-onesuch Keepthistablehandy,andiftheinterpretercomplainsaboutsyntaxerror,checkyourvariablenaming!Likenormallanguage,astatementisaninstruction.InPython,youcanexecuteprimarilytwokindsofstatements:printandassignment.Theformerproducesavaluewhilethelaterdoesnothing.Whenyouwriteastatement,theinterpreterexecutesitandtriestodisplayprint(3) t= print Theabovecodewillproducethe TheassignmentstatementusedforcreatingavariableproducesnoAsinlanguage,anexpressionisacompletethought,withapremiseandaconclusion.Inpython,anexpressionhasinputs,adefined/expecteduseofthoseinputs,andanexpectedwayofeitherdirectlydisplayinganoutputorcomputingittodisplayanoutput.Generally,meaningfulexpressionsareacombinationofvariables,values,statements,andoperatorsthatforcestheinterpretertoevaluateitanddisplayresults:>>>>>>1+2Avalueandavariableitselfaresimpleexpressionsin>>>>>>>>>However,theseexpressionssimplyprint/displaytheexpression.Evaluatinganexpressionisnotsimilartosimplyprintingavalue.Takethe>>>message>>>message=“Writing>>>“WritingNoticehowthequotationmarksaredisplayedintheoutput.However,whenusingprint(),onlythecontentsofthestringaredisplayed:>>>>>>printWritingThisisbecausetheprint()statementfetchesthevalueofthevariable(theNow,anexpressionallbyitselfisalegalstatement.Youcanwriteasmanyasyouwant,butunlessyouusecertainoperatorsandcommandstocommunicatethepurposeoftheexpression,NOOUTPUTwillbedisplayed.Forinstance:“Python,“Python,13+NooutputwillbeThisiswhereoperatorsandoperandscomeintoOperatorsandAcodeissupposedtoperformcertaincomputationsontheexpressionstogeneratepredictableoutputs.Computationsareperformedusingoperators—specialsymbolswhichyoumaythinkofasshortformsfordifferentThevaluethattheoperatorusesiscalledanoperand.Herearesomet-t-(1+2+3)*(6-Howthesymbolshavebeenused+,-,/,*(formultiplication)arethesamewaytheyareusedinmathematics.Now,whenavariableisusedwithoperator(s)tocreateanexpression,theinterpreterfetchesandcomputesthevalueassignedtothatvariable.However,thereisacaveat.Thoughaddition,multiplication,subtraction,andexponentiation(representedbythedoubleasteriskoperator**)haveasingleuseandgenerateanexpectedresult,divisiondoesnot.Let’ssaythefollowingexpressionis>>>t>>>t=>>>Butwhatifwantedtoperformanintegerdivisionwheretheanswerisalwaysroundedofftotheclosestintegervalue?Let’s>>>>>>Thisiswhere“//”isusedtoindicateour>>>>>>2Anotherwayof ingistoassigndatatypestotheanswer(afloat),butwewillcometothatlater.OrderOfYoucanusemultipleoperatorsinasingleexpression;howevertheirevaluationisdependedontherulesofprecedence.Pythonfollowsthesameruleasisappliedformathematicaloperators.RememberPEMDAStomemorizetheorder:Parentheses—Expressionsintheparenthesisarealwaysevaluatedfirst.Hence,3*(4-1)is9.Parenthesisarealsoagreatwayformakingiteasiertoreadtheexpressionsuchas(t*100)/60Exponentiation—(**)hasthenexthighestprecedence.Hence,3**1+1is4andnot9,whereas4*1**3is4andnot64.MultiplicationandDivision—Bothhavethesameprecedence,albeithigherthanadditionandsubtractionAdditionandSubtraction—Alsohavethesameprecedence,albeitlowerthanmultiplicationanddivision.Whatifmultiplicationanddivisioncomeinthesameexpression?Forexample:t*100/60Operatorsthathavethesameprecedenceareevaluatedfromtheirappearancefromlefttoright.Hence,intheexpressiont*100/60,multiplicationhappensfirst,followedbyOperationsandGenerally,youcannotperformanymathematicaloperationsonstrings.Thisincludesinstanceswherethestringslooklikenumbers,oronlyhavenumbersinthem.Thefollowingexampleshowsanillegalmathematicaloperationonasetofstrings:mess
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 鄉(xiāng)村合作社與農戶聯(lián)合開發(fā)農業(yè)技術項目協(xié)議
- 通信技術與信號處理練習題
- 技術標準制定合作協(xié)議
- 數學課本九章算術教案
- 教育資源分布報告表
- 西廂記的愛情悲劇征文
- 中學生國學經典故事解讀
- 農業(yè)旅游開發(fā)實施方案
- 數據安全與隱私保護服務協(xié)議約定事項
- 業(yè)務往來預付款協(xié)議書
- 體育測量與評價-第二章-體育測量與評價的基礎理論課件
- 法律服務方案(投標)
- 轉移的危險廢物性狀清單
- 高中英語-新外研版必修一unit5-The-Monarchs-Journey-公開課reading課件
- 建設項目用地預審與選址意見課件講解
- 四年級公共安全教育全冊教案(海峽教育出版社)
- 工程結構通用規(guī)范
- 《構成基礎》PPT課件(190頁PPT)
- 四年級道德與法治從中國制造到中國創(chuàng)造
- 2021-2022新教科版四年級科學下冊全一冊全部課件(共24課)
- 3 棄渣場施工方案
評論
0/150
提交評論