Python Programming: An Introduction to Computer Science

(Nora) #1
88 CHAPTER6.DEFININGFUNCTIONS

Wellnow, thatcertainlyseemstowork,andwe’ve removedsomeoftheduplicationbydefiningthe
happyfunction.However, somethingstilldoesn’t feelquiteright.We have two functions,singFredand
singLucy, thatarealmostidentical. Followingthisapproach,addinga verseforElmerwouldhave us
createasingElmerfunctionthatlooksjustlike thoseforFredandLucy. Can’t wedosomethingaboutthe
proliferationofverses?
NoticethattheonlydifferencebetweensingFredandsingLucyis thenameat theendofthethird
printstatement.Theversesareexactlythesameexceptforthisonechangingpart.We cancollapsethese
two functionstogetherbyusingaparameter. Let’s writea genericfunctioncalledsing.





def sing(person):
happy()
happy()
print "HappyBirthday, dear", person + "."
happy()





Thisfunctionmakesuseofa parameternamedperson. Aparameteris a variablethatis initializedwhen
thefunctionis called.We canusethesingfunctiontoprinta verseforeitherFredorLucy. We justneedto
supplythenameasa parameterwhenweinvoke thefunction.





sing("Fred")
Happy birthday to you!
Happy birthday to you!
Happy Birthday, dearFred.
Happy birthday to you!








sing("Lucy")
Happy birthday to you!
Happy birthday to you!
Happy Birthday, dearLucy.
Happy birthday to you!





Let’s finishwitha programthatsingstoallthreeofourbirthdaypeople.




def main():
sing("Fred")
print
sing("Lucy")
print
sing("Elmer")





It doesn’t getmucheasierthanthat.
Hereis thecompleteprogramasa modulefile.


happy.py


def happy():
print "Happy Birthdayto you!"


def sing(person):
happy()
happy()
print "Happy birthday,dear", person + "."
happy()


def main():
sing("Fred")
print

Free download pdf