51
52
Chapter4. Functions
ofthetwonumbersandplaceditinthelocalfunctionvariablenamed
added
and
usedthe
return
statementtosendthecomputedvaluebacktothecallingcodeas
thefunctionresultwhichwasassignedtothevariable
x
andprintedout.
4.11 Whyfunctions?
Itmaynotbeclearwhyitisworththetroubletodivideaprogramintofunctions.
Thereareseveralreasons:
• Creatinganewfunctiongivesyouanopportunitytonameagroupofstate-
ments,whichmakesyourprogrameasiertoread,understandanddebug.
• Functionscanmakeaprogramsmallerbyeliminatingrepetitivecode.Later,
ifyoumakeachange,youonlyhavetomakeitinoneplace.
• Dividingalongprogramintofunctionsallowsyoutodebugthepartsoneat
atimeandthenassemblethemintoaworkingwhole.
• Well-designedfunctions s areoftenusefulformanyprograms. . Onceyou
writeanddebugone,youcanreuseit.
Throughouttherestofthebook,oftenwewilluseafunctiondefinitiontoexplain
aconcept. Partoftheskillofcreatingandusingfunctionsistohaveafunction
properlycaptureanideasuchas“findthesmallestvalueinalistofvalues”.Later
wewillshowyoucodethatfindsthesmallestinalistofvaluesandwewillpresent
ittoyouasafunctionnamed
min
whichtakesalistofvaluesasitsargumentand
returnsthesmallestvalueinthelist.
4.12 Debugging
Ifyouareusingatexteditortowriteyourscripts,youmightrunintoproblems
withspacesandtabs. Thebestwaytoavoidtheseproblemsis s tousespaces
exclusively(notabs).MosttexteditorsthatknowaboutPythondothisbydefault,
butsomedon’t.
Tabsandspacesareusuallyinvisible,whichmakesthemhardtodebug,sotryto
findaneditorthatmanagesindentationforyou.
Also, don’tforgettosaveyourprogrambeforeyourunit. . Somedevelopment
environmentsdothisautomatically,butsomedon’t.Inthatcasetheprogramyou
arelookingatinthetexteditorisnotthesameastheprogramyouarerunning.
Debuggingcantakealongtimeifyoukeeprunningthesame,incorrect,program
overandover!
Makesurethatthecodeyouarelookingatisthecodeyouarerunning.Ifyou’re
notsure,putsomethinglike
print
'
hello
'atthebeginningoftheprogramand
runitagain.Ifyoudon’tsee
hello
,you’renotrunningtherightprogram!