Indentation in Python with Examples - freeCodeCamp

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

To indicate a block of code in Python, you must indent each line of the block by the same amount. The two blocks of code in our example ... Search Submityoursearchquery Forum Donate Learntocode—free3,000-hourcurriculum ItisgenerallygoodpracticeforyounottomixtabsandspaceswhencodinginPython.DoingthiscanpossiblycauseaTabError,andyourprogramwillcrash.Beconsistentwhenyoucode-chooseeithertoindentusingtabsorspacesandfollowyourchosenconventionthroughoutyourprogram.CodeBlocksandIndentationOneofthemostdistinctivefeaturesofPythonisitsuseofindentationtomarkblocksofcode.Considertheif-statementfromoursimplepassword-checkingprogram:ifpwd=='apple': print('Loggingon...') else: print('Incorrectpassword.') print('Alldone!')Thelinesprint(‘Loggingon…’)andprint(‘Incorrectpassword.’)aretwoseparatecodeblocks.Theseoneshappentobeonlyasinglelinelong,butPythonletsyouwritecodeblocksconsistingofanynumberofstatements.ToindicateablockofcodeinPython,youmustindenteachlineoftheblockbythesameamount.Thetwoblocksofcodeinourexampleif-statementarebothindentedfourspaces,whichisatypicalamountofindentationforPython.Inmostotherprogramminglanguages,indentationisusedonlytohelpmakethecodelookpretty.ButinPython,itisrequiredforindicatingwhatblockofcodeastatementbelongsto.Forinstance,thefinalprint(‘Alldone!’)isnotindented,andsoisnotpartoftheelse-block.Programmersfamiliarwithotherlanguagesoftenbristleatthethoughtthatindentationmatters:Manyprogrammerslikethefreedomtoformattheircodehowtheyplease.However,Pythonindentationrulesarequitesimple,andmostprogrammersalreadyuseindentationtomaketheircodereadable.Pythonsimplytakesthisideaonestepfurtherandgivesmeaningtotheindentation.If/elif-statementsAnif/elif-statementisageneralizedif-statementwithmorethanonecondition.Itisusedformakingcomplexdecisions.Forexample,supposeanairlinehasthefollowing“child”ticketrates:Kids2yearsoldoryoungerflyforfree,kidsolderthan2butyoungerthan13payadiscountedchildfare,andanyone13yearsorolderpaysaregularadultfare.Thefollowingprogramdetermineshowmuchapassengershouldpay:#airfare.py age=int(input('Howoldareyou?')) ifage<=2: print('free') elif2



請為這篇文章評分?