Lesson 04-06: Functions & Synchronous Execution¶
Learning Target: I can predict function code execution.
One Instruction At A Time¶
In this book, we’ll be running python synchronously on a single thread. What this means is that our programs will only ever be executing one instruction at a time, going in the exact order that we tell it to. Before we learned functions, programs were easy to follow. We would read instructions top-down, occasionally going back up to repeat a loop, or skipping some code in a conditional. However, with functions, suddenly we’re all over the place! Being able to manually trace through our code is vital to efficient debugging.
In learning how the code moves around, our best friend here is codelens, or PythonTutor.
Let’s look at a simple example of a function call and determine what the program is doing:
There are six steps here. Let’s break them down (following the red arrow):
- Define the function
add2
. - Call the function
add2
with arguments5
and6
. - Entering the function assign the arguments
5
and6
to the variablesx
andy
respectively. - Return the sum of
x+y
, which is11
. 11
gets returned to the function call on line 4.- Now that we’ve evaluated the function, we continue with line 4 by storing the value
11
insum
. - (last) We print out the value of
sum
, which is11
.
Notice how on line 4, when we reach the function call, we save our spot while we execute the function - and when we’re done with the function, we go right back to where we were (on line 4). This principle is very important when trying to trace through code. Here’s a slightly more complex one:
In this one, as you step through the code, you’ll notice that the function is_integer()
is called first, and is_even()
is called right after it. That’s because the conditional is_integer(num) and is_even(num)
requires both functions to be evaluated in order to be evaluated as a whole, so it goes through each function in the order of operations (in this case, and
, which is just left-to-right). Each time, when the function completes, it returns to where it was called to look for its next instruction.
Checks For Understanding¶
Q#1¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | def func1(n):
if n > 0:
return True
else:
return False
def func2(n):
if n < 0:
return True
else:
return False
num = -2
if func1(num):
print("alpha")
elif func2(num):
print("beta")
else:
print("gamma")
|
What will be printed from running the code above?
What will be printed from running the code above if line 13 was num = 0
instead?