12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

3.7. Flow of execution 21def repeat_lyrics():print_lyrics()print_lyrics()repeat_lyrics()This program contains two function definitions: print_lyrics and repeat_lyrics. Functiondefinitions get executed just like other statements, but the effect is to create function objects. Thestatements inside the function do not get executed until the function is called, and the functiondefinition generates no output.As you might expect, you have to create a function before you can execute it. In other words, thefunction definition has tobe executed beforethe firsttimeitiscalled.Exercise 3.1 Move the last line of this program to the top, so the function call appears before thedefinitions. Run theprogram and see what error message you get.Exercise 3.2 Move the function call back to the bottom and move the definition of print_lyricsafter thedefinition ofrepeat_lyrics. What happens when you runthisprogram?3.7 FlowofexecutionInorder to ensure that a function is defined before itsfirst use, you have to know the order in whichstatements are executed, which iscalled the flow ofexecution.Executionalwaysbeginsatthefirststatementoftheprogram. Statementsareexecutedoneatatime,inorder from toptobottom.Functiondefinitionsdonotaltertheflowofexecutionoftheprogram,butrememberthatstatementsinsidethe function arenot executed until the function iscalled.A function call is like a detour in the flow of execution. Instead of going to the next statement, theflow jumps to the body of the function, executes all the statements there, and then comes back topick up where itleftoff.That sounds simple enough, until you remember that one function can call another. While in themiddle of one function, the program might have to execute the statements in another function. Butwhileexecuting that new function, the program might have toexecute yet another function!Fortunately, <strong>Python</strong> is good at keeping track of where it is, so each time a function completes, theprogram picks up where it left off in the function that called it. When it gets to the end of theprogram, itterminates.What’sthemoralofthissordidtale? Whenyoureadaprogram,youdon’talwayswanttoreadfromtoptobottom. Sometimes it makes moresenseif you follow theflow of execution.3.8 Parametersand argumentsSome of the built-in functions we have seen require arguments. For example, when you callmath.sin you pass a number as an argument. Some functions take more than one argument:math.powtakes two,the base and theexponent.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!