




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2024年陪诊师考试省时攻略与试题及答案
- 实施城市公交线路优化调整计划
- 兽医疾病控制方法试题及答案
- 2025年份第一季度餐饮业跨平台评价数据迁移保密条款
- 2025年贵州省安全员-A证考试题库附答案
- 兽医行业投资与市场拓展策略试题及答案
- 体育训练运动营养与恢复策略研究题
- 复习安排2024人力资源管理师考试试题及答案
- 2024年矿产资源开发试题及答案
- 高精度设备维修与保养手册
- 大学生创新创业训练计划项目申报书(模板)
- 争做最美班级主题班会课件
- 铁路职工政治理论应知应会题库
- 2020年交安A、B、C证(公路)考试题库1088题(含答案)
- 墙绘验收单模板
- 节后复工检查表
- 财务有哪些制度要上墙
- 医学教学课件:软组织肿瘤影像诊断
- 矿山矿石损失与贫化管理规程
- 安全生产晨会管理制度
- 直线导轨装配文档课件
评论
0/150
提交评论