Indentation in Python with Examples - freeCodeCamp
文章推薦指數: 80 %
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
延伸文章資訊
- 1From Blocks to Code with Trinket! - An Hour of Python
Starting with Blocks, we look at the code underneath and learn some basics of Python! Let's Go! S...
- 2Python Code Block - What Is It? - YouTube
- 3Block - Data Independent
- 4What is a block of code? - Python FAQ - Codecademy Forums
A block of code is composed of several statements that are intended to execute when certain condi...
- 54. 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 ...