Python Programming: An Introduction to Computer Science

(Nora) #1
6.5.FUNCTIONSTHAT RETURNVALUES 93

Theneteffectis asif thefunctionbodyhadbeenprefacedwiththreeassignmentstatements.


window = win
year = 0
height = principal


Youmustalwaysbecarefulwhencallinga functionthatyougettheactualparametersinthecorrectorderto
matchthefunctiondefinition.


6.5 FunctionsthatReturnValues.


Youhave seenthatparameterpassingprovidesa mechanismforinitializingthevariablesina function.Ina
way, parametersactasinputstoa function.We cancalla functionmany timesandgetdifferentresultsby
changingtheinputparameters.
Sometimeswealsowanttogetinformationbackoutofa function. Thisisaccomplishedbyhaving
functionsreturna valuetothecaller. Youhave alreadyseennumerousexamplesofthistypeoffunction.For
example,considerthiscalltothesqrtfunctionfromthemathlibrary.


discRt = math.sqrt(bb- 4a*c)


Herethevalueofbb - 4a*cistheactualparameterofmath.sqrt. Thisfunctioncalloccurson
therightsideofanassignmentstatement;thatmeansit is anexpression.Themath.sqrtfunctionmust
somehowproducea valuethatis thenassignedtothevariablediscRt. Technically, wesaythatsqrt
returnsthesquarerootofitsargument.
It’s veryeasytowritefunctionsthatreturnvalues.Here’s anexamplevalue-returningfunctionthatdoes
theoppositeofsqrt; it returnsthesquareofitsargument.


def square(x):
return x * x


Thebodyofthisfunctionconsistsofa singlereturnstatement.WhenPythonencountersreturn, it exits
thefunctionandreturnscontroltothepointwherethefunctionwascalled.Inaddition,thevalue(s)provided
inthereturnstatementaresentbacktothecallerasanexpressionresult.
We canuseoursquarefunctionany placethatanexpressionwouldbelegal.Herearesomeinteractive
examples.





square(3)
9
print square(4)
16
x = 5
y = square(x)
print y
25
print square(x)+ square(3)
34





Let’s usethesquarefunctiontowriteanotherfunctionthatfindsthedistancebetweentwo points.Given
two points



x 1 y 1  and


x 2 y 2 , thedistancebetweenthemis calculatedfromthePythagoreanTheoremas



x 2  x 1 ^2 


y 2  y 1 ^2. Hereis a PythonfunctiontocomputethedistancebetweentwoPointobjects.

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



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


Usingthedistancefunction,wecanaugmenttheinteractive triangleprogramfromlastchapterto
calculatetheperimeterofthetriangle.Here’s thecompleteprogram:

Free download pdf