yego.me
💡 Stop wasting time. Read Youtube instead of watch. Download Chrome Extension

Tracing function calls | Intro to CS - Python | Khan Academy


4m read
·Nov 10, 2024

What exactly happens when the computer executes a function call? Well, let's trace a program with a function definition to find out.

When we run the program, the computer, as normal, reads the program line by line starting at the top of the file. When the computer sees the keyword def, it goes off to a short-term memory and defines a new function. We can think of this as the computer copying the function body into a place in memory and then it tags that location with the function name and the number of parameters. The computer technically makes some optimizations here, but we can think of it the same way. Effectively, the computer has just learned a new task named get_greeting.

However, the computer does not yet execute any of these lines of code. It's just learning the new task right now, not doing it. When it's done learning, it skips to the next line of code after the function definition. Remember that Python's all about that indentation, so these lines of code are all part of the function body since they're indented over from the function header. To make this a bit easier to see, I'm going to scroll the program up, but those lines of code still exist here.

We just have a normal variable assignment, and since the right hand side is already a single value, we're ready to store that in short-term memory. The computer stores the value six and then tags that location with the name last_chatted. Next line, we have another variable assignment, but before we store, we need to simplify down the right hand side to a single value. As with all expressions, we start simplifying with the parentheses, so we substitute in the current value of last_chatted and add one.

Now that our arguments are down to single values, we're ready to call the function. To start, the computer checks its memory to see if it knows the name get_greeting with two input parameters. In this case, it does, so it loads those instructions to execute. The first thing the computer does when it calls a function is create a new stack frame. A stack frame is its own isolated chunk of short-term memory.

When the computer executes a function, it treats it as its own little subprogram. It doesn't want that subprogram to muck with the state of the larger program, so it ropes it off from the rest of its memory. Anything that was stored before is still there; we just don't get access to it right now. First, we need to store the arguments that were passed in. To do this, the computer copies the argument values into new locations in its stack frame. Then it tags each location with a corresponding parameter name. This is order dependent, so the first argument in the function call gets assigned to the first parameter in the function header.

Then we're just executing these lines of code per normal. Seven is not less than one, so this evaluates to false, and we jump to the else branch. We assign the string "always good to see you" to a new variable greeting in our own stack frame. Then we're at the return statement. The return keyword tells the computer to exit the function and return execution back to wherever the function was called. But first, it needs to calculate the return value.

So we need to simplify down this expression. We plug in the current values of greeting and catchphrase, and then we concatenate everything together. Now, the computer jumps execution back to the call site, taking that return value with it. However, this stack frame does not get to come back. We've effectively terminated this subprogram, so its short-term memory gets cleared. We take that return value to go as we pop off that stack frame.

What that means in practice is that this function call expression evaluates down to the return value. So now we have the statement response is assigned the value "always good to see you, pal". We have a single value now, so we can go off and create that variable. Because we cleared that stack frame, we're back in our global memory space, so we store response there.

Now finally we get to move to the next line. This just reassigns the variable last_chatted to the value zero. Easy. Here we've got another function call to get_greeting, so we just do the same thing. Our two arguments are already simplified down to single values, so we can just go ahead and call the function. The computer loads the instructions associated with get_greeting from memory and like before, it also creates a new stack frame. It copies the arguments into the corresponding parameters and then continues on to execute the function body.

dayon spoken contains zero this time, so we execute the if branch, and then we're back at the return statement. This string expression evaluates down to "oh, it's you again, bin". Once we have that single value, we return back to the call site, popping off that stack frame.

Now this is a bit of a weird one. This function call expression evaluates down to that string we returned. However, this line of code doesn't do anything with that string. I wouldn't recommend writing programs like this because we're wasting the computer's time calculating a result that we don't need. But I took the creative liberty here so I could show what happens. This instruction is complete, so we move to the next line.

Unfortunately, since we didn't store it, that function call return value gets lost to time. We are back in our global memory space and we have a print statement. We load in the value of response and then we concatenate it to the first string. Once we have that single value, we go ahead and display it in the console, and then we hit the last line.

So the computer clears out its global memory and terminates the program. Notice that that function definition gets cleared out from memory too. The computer doesn't remember user-defined functions across program executions, so we need that function definition to teach it how to get_greeting every time.

More Articles

View All
Le Châtelier's principle | Reaction rates and equilibrium | High school chemistry | Khan Academy
Let’s imagine a reaction that is in equilibrium: A plus B can react to form C plus D, or you could go the other way around. C plus D could react to form A plus B. We assume that they’ve all been hanging around long enough for this to be in equilibrium, so…
Teaching a Fixated Dog to Focus | Cesar Millan: Better Human Better Dog
For me, it’s easier to rehabilitate an aggressive dog than a fixated dog. While working with fixated and overexcited kelpie Shadow, Caesar discovers the dog has forgotten how to behave like a dog. “That’s my girl! Let’s go swimming!” To prevent aggressio…
Staying in the Lines | Rocky Mountain Law
Have you had anything to drink at all in the last 24 hours? No. Okay, have you had any drugs or anything at all in the last 24 hours? Okay, what’s your native language that you speak? Uh, Pabi. And you understand English? Yeah, for the most part. Very muc…
Let's Talk About Clean Energy | Breakthrough
I believe that there is energy, clean safe energy all around us, and that it is our opportunity now and our obligation to find ways to access it. I’ve always had great fun converting other people’s work into my own. When I was a kid, I liked coloring book…
Galvanic (voltaic) cells | Applications of thermodynamics | AP Chemistry | Khan Academy
Galvanic cells, which are also called voltaic cells, use a thermodynamically favorable reaction to generate an electric current. Before we look at a diagram of a galvanic or voltaic cell, let’s first look at the half reactions that are going to be used in…
Making Music and Art Through Machine Learning - Doug Eck of Magenta
Hey, this is Craig Cannon and you’re listening to a Y Combinator’s podcast. Today’s episode is with Doug Eck. Doug’s a research scientist at Google, and he’s working on Magenta, which is a project making music and art through machine learning. Their goal …