98 CHAPTER6.DEFININGFUNCTIONS
- Functionscanbethoughtofasminiature(sub)programsinsideofotherprograms. Like any other
program,wecanthinkoffunctionsashavinginputandoutputtocommunicatewiththemainprogram.
(a)How doesa programprovide“input”tooneofitsfunctions?
(b)How doesa functionprovide“output”totheprogram?
- Considerthisverysimplefunction:
def cube(x):
answer = x * x * x
return answer
(a)Whatdoesthisfunctiondo?
(b)Show how a programcouldusethisfunctiontoprintthevalueofy^3 , assumingyis a variable.
(c)Hereis a fragmentofa programthatusesthisfunction:
answer = 4
result = cube(3)
print answer, result
Theoutputfromthisfragmentis4 27. Explainwhytheoutputis not27 27, eventhoughcube
seemstochangethevalueofanswerto 27.
- Writea programtoprintthelyricsofthesong“OldMacDonald.” Yourprogramshouldprintthelyrics
forfive differentanimals,similartotheexampleversebelow.
OldMacDonaldhada farm,Ee-igh,Ee-igh,Oh!
Andonthatfarmhehada cow, Ee-igh,Ee-igh,Oh!
Witha moo,moohereanda moo,moothere.
Herea moo,therea moo,everywherea moo,moo.
OldMacDonaldhada farm,Ee-igh,Ee-igh,Oh!
- Writea programtoprintthelyricsfortenversesof“TheAntsGoMarching.” A couplesampleverses
aregivenbelow. Youmaychooseyourownactivityforthelittleoneineachverse,butbesureto
choosesomethingthatmakestherhymework(oralmostwork).
Theantsgomarchingonebyone,hurrah!hurrah!
Theantsgomarchingonebyone,hurrah!hurrah!
Theantsgomarchingonebyone.
Thelittleonestopstosuckhisthumb
Andthey allgomarchingdown...
Inthegound...
To getout....
Oftherain.
Boom!Boom!Boom!
Theantsgomarchingtwo bytwo, hurrah!hurrah!
Theantsgomarchingtwo bytwo, hurrah!hurrah!
Theantsgomarchingtwo bytwo.
Thelittleonestopstotiehisshoe
Andthey allgomarchingdown...
Intheground...
To getout...
Oftherain.
Boom!Boom!Boom!