Grokking Algorithms


def greet2(name): print “how are you, “ + name + “?” def



Yüklə 348,95 Kb.
Pdf görüntüsü
səhifə29/122
tarix05.12.2023
ölçüsü348,95 Kb.
#173611
1   ...   25   26   27   28   29   30   31   32   ...   122
grokking-algorithms-illustrated-programmers-curious

def greet2(name):
print “how are you, “ + name + “?”
def bye():
print “ok bye!”
Let’s walk through what happens when you call a function.
Suppose you call 
greet(“maggie”)
. First, your computer allocates a box 
of memory for that function call.
Now let’s use the memory. The variable 
name
is set to “maggie”. That 
needs to be saved in memory.
Note
print
is a function in Python, but to make things easier for this example,
we’re pretending it isn’t. Just play along.


44
Chapter 3
 
 
I
 
 
Recursion
Every time you make a function call, your computer saves the values 
for all the variables for that call in memory like this. Next, you print
hello, maggie!
Then you call 
greet2(“maggie”). 
Again, your 
computer allocates a box of memory for this function call.
Your computer is using a stack for these boxes. The second box is added 
on top of the first one. You print 
how are you, maggie?
Then you 
return from the function call. When this happens, the box on top of the 
stack gets popped off. 
Now the topmost box on the stack is for the 
greet
function, which 
means you returned back to the 
greet
function. When you called the 
greet2
function, the 
greet
function was
 partially completed. 
This is 
the big idea behind this section: 
when you call a function from another 
function, the calling function is paused in a partially completed state. 
All 
the values of the variables for that function are still stored in memory. 
Now that you’re done with the 
greet2
function, you’re back to the 
greet
function, and you pick up where you left off. First you print 
getting ready to say bye…
. You call the 
bye
function.


45
The stack
A box for that function is added to the top of the stack. Then you print 
ok bye!
and return from the function call.
And you’re back to the
greet
function. There’s nothing else to be done, 
so you return from the 
greet
function too. This stack, used to save the 
variables for multiple functions, is called the 
call stack
.

Yüklə 348,95 Kb.

Dostları ilə paylaş:
1   ...   25   26   27   28   29   30   31   32   ...   122




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin