4. Structuring with Indentation | Python Tutorial
文章推薦指數: 80 %
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
延伸文章資訊
- 1Welcome to BlockPy! - Virginia Tech
BlockPy is a web-based Python environment that lets you work with blocks, text, or both. Designed...
- 2Nested Program Blocks (Python) - IBM
From within Python, you can submit command syntax containing a BEGIN PROGRAM block, thus allowing...
- 3自己做Python 的With Block - Eugene Yang
其實它的用處還有很多有趣的作法呢:) 其實with 他是個在python 的code block 前後幫你偷偷做事情的東西,在經典的開檔案例子中,他就會 ...
- 44. Execution model — Python 3.10.4 documentation
A Python program is constructed from code blocks. A block is a piece of Python program text that ...
- 5EasyPython Code Python with Blocks - easycoding.tn
Code Python with Blocks. English, Français. Blocks, Python, XML, easycoding.tn Offline version. L...