4. Structuring with Indentation | Python Tutorial

文章推薦指數: 80 %
投票人數:10人

A block is a group of statements in a program or script. Usually, it consists of at least one statement and declarations for the block, ... PythonTrainingCourses LivePythonclassesbyhighlyexperiencedinstructors: Instructor-ledtrainingcoursesbyBerndKlein InthisPythonTutorialchapter IntrotoPythonTutorial HistoryandPhilosophyofPython TheInterpreter,anInteractiveShell ExecuteaScript StructuringwithIndentation AssignmentExpressions DataTypesandVariables Operators SequentialDataTypes ListManipulation ShallowandDeepCopy Dictionaries SetsandFrozenSets SetsExamples KeyboardInput ConditionalStatements StructuralPatternMatching WhileLoops ForLoops OutputwithPrint FormattedOutput WorkingwithDictionariesandwhileLoops Functions PassingArguments Namespaces Globalvs.LocalVariablesandNamespaces FileManagement ModularProgrammingandModules Packages ErrorsandExceptionHandling ClassroomTrainingCourses ThiswebsitecontainsafreeandextensiveonlinetutorialbyBerndKlein,usingmaterialfromhisclassroomPythontrainingcourses. Ifyouareinterestedinaninstructor-ledclassroomtrainingcourse,havealookatthesePythonclasses: Instructor-ledtrainingcoursebyBerndKleinatBodenseo Image©kabliczech-Fotolia.com DeutscheAusgabe DEStrukturierungundBlöcke TürkçeVersiyon TRGirintilerileYapıOluşturmak Pageauthor ThispagewaswrittenbyBerndKlein. BerndisanexperiencedcomputerscientistwithahistoryofworkingintheeducationmanagementindustryandisskilledinPython,Perl,ComputerScience,andC++.HehasaDipl.-Informatiker/MasterDegreefocusedinComputerSciencefromSaarlandUniversity. BerndKleinonFacebook BerndKleinonLinkedIn python-courseonFacebook PDFversion PDFversionofthissite HelpNeeded Thiswebsiteisfreeofannoyingads.Wewanttokeepitlikethis.Youcanhelpwithyourdonation: Theneedfordonations 4.StructuringwithIndentation ByBerndKlein.Lastmodified:01Feb2022. Onthispage➤ Blocks Ablockisagroupofstatementsinaprogramorscript.Usually,itconsistsofatleastonestatementanddeclarationsfortheblock,dependingontheprogrammingorscriptinglanguage.Alanguagewhichallowsgroupingwithblocks,iscalledablockstructuredlanguage.Generally,blockscancontainblocksaswell,sowegetanestedblockstructure.Ablockinascriptorprogramfunctionsasameanstogroupstatementstobetreatedasiftheywereonestatement.Inmanycases,italsoservesasawaytolimitthelexicalscopeofvariablesandfunctions. Initially,insimplelanguageslikeBasicandFortran,therewasnowayofexplicitlyusingblockstructures.Programmershadtorelyon"goto"structures,nowadaysfrownedupon,because"Gotoprograms"turneasilyintospaghetticode,i.e.tangledandinscrutablecontrolstructures. BlockstructureswerefirstformalizedinALGOLasacompoundstatement. Programminglanguages,suchasALGOL,Pascal,andothers,usuallyusecertainmethodstogroupstatementsintoblocks: begin...end AcodesnippetinPascaltoshowthisusageofblocks: withptoNode^do begin x:=42; y:='X'; end; do...done if...fie.g.BourneandBashshell Braces(alsocalledcurlybrackets):{...}Byfarthemostcommonapproach,usedbyC,C++,Perl,Java,andmanyotherprogramminglanguages,istheuseofbraces.ThefollowingexampleshowsaconditionalstatementinC: if(x==42){ printf("TheAnswertotheUltimateQuestionofLife,theUniverse,andEverything\n"); }else{ printf("Justanumber!\n"); } Theindentationsinthiscodefragmentarenotnecessary.Sothecodecouldbewritten-offendingcommondecency-as if(x==42){printf("TheAnswertotheUltimateQuestionofLife,theUniverse,andEverything\n");}else{printf("Justanumber!\n");} Please,keepthisinmindtounderstandtheadvantagesofPython! LivePythontraining Enjoyingthispage?WeofferlivePythontrainingcoursescoveringthecontentofthissite. See:LivePythoncoursesoverview Enrolhere IndentingCode Pythonusesadifferentprinciple.Pythonprogramsgetstructuredthroughindentation,i.e.codeblocksaredefinedbytheirindentation.Okaythat'swhatweexpectfromanyprogramcode,isn'tit?Yes,butinthecaseofPythonit'salanguagerequirement,notamatterofstyle.Thisprinciplemakesiteasiertoreadandunderstandotherpeople'sPythoncode. So,howdoesitwork?Allstatementswiththesamedistancetotherightbelongtothesameblockofcode,i.e.thestatementswithinablocklineupvertically.Theblockendsatalinelessindentedortheendofthefile.Ifablockhastobemoredeeplynested,itissimplyindentedfurthertotheright. Beginnersarenotsupposedtounderstandthefollowingexample,becausewehaven'tintroducedmostoftheusedstructures,likeconditionalstatementsandloops.Pleaseseethefollowingchaptersaboutloopsandconditionalstatementsforexplanations.TheprogramimplementsanalgorithmtocalculatePythagoreantriples.YouwillfindanexplanationofthePythagoreannumbersinourchapteronforloops. frommathimportsqrt n=input("MaximumNumber?") n=int(n)+1 forainrange(1,n): forbinrange(a,n): c_square=a**2+b**2 c=int(sqrt(c_square)) if((c_square-c**2)==0): print(a,b,c) OUTPUT: 345 51213 6810 81517 91215 121620 152025 ThereisanotheraspectofstructuringinPython,whichwehaven'tmentionedsofar,whichyoucanseeintheexample.LoopsandConditionalstatementsendwithacolon":"-thesameistrueforfunctionsandotherstructuresintroducingblocks.Allinall,Pythonstructuresbycolonsandindentation. LivePythontraining Enjoyingthispage?WeofferlivePythontrainingcoursescoveringthecontentofthissite. See:LivePythoncoursesoverview UpcomingonlineCourses PythonBasicsforBeginners 16May2022to20May2022 29Aug2022to02Sep2022 17Oct2022to21Oct2022 IntensiveAdvancedCourse 30May2022to03Jun2022 29Aug2022to02Sep2022 17Oct2022to21Oct2022 PythonforEngineersandScientists 16May2022to20May2022 29Aug2022to02Sep2022 17Oct2022to21Oct2022 ObjectOrientedProgrammingwithPython 01Jun2022to03Jun2022 31Aug2022to02Sep2022 19Oct2022to21Oct2022 Enrolhere



請為這篇文章評分?