Python Programming: An Introduction to Computer Science

(Nora) #1
6.2.FUNCTIONS,INFORMALLY 87

Obviously, thereis someduplicatedcodeinthisprogram.Forsucha simpleprogram,that’s nota big
deal,butevenhereit’s a bitannoyingtokeepretypingthesameline.Let’s introducea functionthatprints
thelyricsofthefirst,second,andfourthlines.





def happy():
print "Happybirthday to you!"





We have defineda new functioncalledhappy. Hereis anexampleofwhatit does.





happy()
Happy birthday to you!





InvokingthehappycommandcausesPythontoprinta lineofthesong.
Now wecanredotheverseforFredusinghappy. Let’s callournew versionsingFred.





def singFred():
happy()
happy()
print "Happybirthday, dear Fred."
happy()





Thisversionrequiredmuchlesstyping,thankstothehappycommand.Let’s tryprintingthelyricsforFred
justtomake sureit works.





singFred()
Happy birthday to you!
Happy birthday to you!
Happy birthday, dearFred.
Happy birthday to you!





Sofar, sogood.Now supposethatit’s alsoLucy’s birthday, andwewantto singa verseforFredfollowed
bya verseforLucy. We’ve alreadygottheverseforFred;wecanprepareoneforLucy aswell.





def singLucy():
happy()
happy()
print "Happybirthday, dear Lucy."
happy()





Now wecanwriteamainprogramthatsingstobothFredandLucy.





def main():
singFred()
print
singLucy()





Thebareprintbetweenthetwo functioncallsputsa spacebetweentheversesinouroutput.Andhere’s
thefinalproductinaction.





main()
Happy birthday to you!
Happy birthday to you!
Happy birthday, dearFred.
Happy birthday to you!





Happy birthday to you!
Happy birthday to you!
Happy birthday, dearLucy.
Happy birthday to you!

Free download pdf