πββοΈHow Python Executes a Function Call
Running through what Python does!
There's two stages at which Python interacts with a function βΒ when it first finds and creates the function, and when the function is called. In this chapter, we'll go over what Python does behind the scenes in each of these stages.
Creating the Function
Consider the following function, which accepts two value, prints one, and returns the double of that other.
When Python first sees this definition, it adds a function f
to the list of functions that can be called in the program, and it remembers that this function f
accepts two argument, but it does not read the inside of the function. Everything that is tabbed is ignored by Python. To see this, consider another function that should error:
However, if this function is never called, it will never error.
Calling the Function
Now that the function is created, we should go ahead and call it!
What is Python doing when it first sees the function call on Line 6? First, it goes looking for the function f
βΒ and throws an error if it doesn't find it. Try changing line 6 to read something like g(a)
to see Python get mad.
Next, it evaluates all the arguments that are passed into the function call. It evaluates a
to be equal to 7
and evaluates 4+5*2
to be equal to 14
. Once these are evaluated, Python checks if the number of arguments given to the function β and errors if the numbers do not match the number of inputs the function accepts.
If all these checks pass, congratulations! The function call is made. If there are any errors in the code within the function, this is where they will get mad.
The inputs are set to the values passed in βΒ x=7 and y=14
here. The code within the function in executed to completion β we print 14
and return 7*2 = 14
.
Python executes a function until the first return statement that it finds.
Last updated