Python Programming: An Introduction to Computer Science

(Nora) #1
6.6.FUNCTIONSANDPROGRAMSTRUCTURE 95

Aswithparameters,whenmultiplevaluesarereturnedfroma function,they areassignedtovariablesby
position.Inthisexample,swillgetthefirstvaluelistedinthereturn(sum), anddwillgetthesecond
value(diff).
That’s justaboutallthereis toknow aboutfunctionsinPython.Thereis one“gotcha”towarnyouabout.
Technically, allfunctionsin Pythonreturna value,regardlessofwhetherornotthefunctionactuallycontains
areturnstatement. Functionswithoutareturnalwayshandbacka specialobject,denotedNone.
Thisobjectis oftenusedasa sortofdefaultvalueforvariablesthatdon’t currentlyholdanythinguseful.A
commonmistake thatnew (andnot-so-new)programmersmake is writingwhatshouldbea value-returning
functionbutforgettingtoincludeareturnstatementat theend.
Supposeweforgettoincludethereturnstatementat theendofthedistancefunction.


def distance(p1, p2):
dist = math.sqrt(square(p2.getX() - p1.getX())



  • square(p2.getY()- p1.getY())


RunningtherevisedtriangleprogramwiththisversionofdistancegeneratesthisPythonerrormessage.


Traceback (innermostlast):
File "", line1, in?
File "triangle2err.py",line 44, in?
main()
File "triangle2err.py",line 37, in main
perim = distance(p1,p2)+ distance(p2,p3) + distance(p3,p1)
TypeError: bad operandtype(s) for +


Theproblemhereis thatthisversionofdistancedoesnotreturna number, butalwayshandsbackthe
valueNone. Additionis notdefinedforNone, andsoPythoncomplains.If yourvalue-returningfunctions
areproducingstrangeerrormessages,checktomake sureyourememberedtoincludethereturn.


6.6 FunctionsandProgramStructure.


Sofar, wehave beendiscussingfunctionsasa mechanismforreducingcodeduplication,thusshortening
andsimplifyingourprograms.Surprisingly, functionsareoftenusedevenwhendoingsoactuallymakesthe
programlonger. A secondreasonforusingfunctionsis tomake programsmoremodular.
Asthealgorithmsthatyoudesigngetmorecomplex,it getsmoreandmoredifficulttomake senseout
ofprograms. Humansareprettygoodatkeepingtrackofeighttotenthingsata time. Whenpresented
withanalgorithmthatishundredsoflineslong,eventhebestprogrammerswillthrowuptheirhandsin
bewilderment.
Onewaytodealwiththiscomplexityis tobreakanalgorithmintosmallersubprograms,eachofwhich
makessenseonitsown. I’ll have a lotmoretosayaboutthislaterwhenwediscussprogramdesignin
Chapter9.Fornow, we’ll justtake a lookat anexample.Let’s returntothefuturevalueproblemonemore
time.Hereis themainprogramasweleftit:


def main():


Introduction


print "This programplots the growth of a 10-year investment."


# Get principaland interest rate
principal = input("Enterthe initial principal: ")
apr = input("Enterthe annualized interest rate: ")

# Create a graphicswindow with labels on left edge
win = GraphWin("Investment Growth Chart", 320, 240)
win.setBackground("white")
win.setCoords(-1.75,-200, 11.5, 10400)
Free download pdf