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

Tracing loop execution | Intro to CS - Python | Khan Academy


4m read
·Nov 10, 2024

What exactly is happening behind the scenes when the computer executes a while loop? Let's trace a while loop step by step to find out.

Before we start, let's see if we can get some intuition for how many times this loop repeats. To count repetitions, we just need to look at the loop variable. What value does it start at before the loop? What value does it stop at to terminate the loop? And what value does it update by on each loop iteration?

Here we see that our loop variable is called pin, and it's initialized to the empty string. The loop condition then is checking the length of the string pin, and it's comparing it to the number four, which means this is the length that we'll stop at. Because pin is initialized to the empty string, we're starting out at length zero.

Now we just need to look for how pin gets updated inside the loop body. The assignment statement here looks like it's concatenating a new digit onto pin on each iteration, so the length of pin would be increasing by one each time. If we start at zero, we stop when we get to four. We increment by one, so this loop will repeat four times.

Now let's double check that work by tracing the full execution. As usual, the computer starts executing at the first line of the program. Here we have an import statement, so the computer goes off and loads the code for the random module into its memory. This line initializes the variable pin. The computer goes off to its short-term memory, allocates a new chunk, stores the value of the empty string there, and then tags it with the name pin.

On to the next line. Now we've reached the while loop, so the computer evaluates the loop condition. The variable pin currently contains the value of the empty string, so the length of pin is zero. Zero is less than four, so the loop condition evaluates to true. Because it's true, the computer goes on to execute the loop body.

The loop body is any lines of code that are indented inside the loop. So the next line to execute is this digit assignment statement. We evaluate the right-hand side of the assignment statement first, which calls the randint function. randint generates a random number between these two bounds. This happens randomly, so it'll change on each run of the program. But let's say it returns zero this time.

This is the first time we're assigning to digit, so the computer creates a new variable. Then we move on because this line is indented; it's still inside the while loop. So this is the next line of the loop body. We simplify the right-hand side of the assignment first, substituting in digit, which is the integer zero, and we cast it to a string. So we get the string zero. Then we substitute in pin, which is the empty string, and we concatenate it together. We store that value back in the variable pin, overriding the previous value.

Which line executes next? This print statement is not indented, so it's considered outside of the loop. It's not part of the loop body. That means we're at the bottom of the loop, so the computer jumps execution back to the top of the loop and checks the loop condition again. We substitute in the value of pin, which is now the string 0. We take the length, which is 1. One is less than four, so the loop condition still evaluates to true. That means we're executing the loop body again for a second iteration.

We generate a new random number; let's say it's five this time, assign that to digit, and then we update our loop variable pin. pin currently contains the value zero, and then we concatenate on the string five to get 05. We store that back in pin, and now we're at the bottom of the loop again.

We jump back to the top of the loop and check the loop condition for the third time. pin now contains the value 05, so its length is two. Two is less than four, so the loop condition is true. So we're entering the loop body again. We execute the digit assignment statement; let's say we generate nine this time, we store that in digit, and then we update pin.

Pin is currently 05. We concatenate on the nine and store 059 back. Now back to the top of the loop, the length of pin is now three. Three is less than four, so the loop condition is still true, and we start the fourth iteration. Randint generates a five this time, so we store that in digit, and then we go on to the next line. Pin is now 059. We concatenate on the string five and store that back in pin.

Once again, we find ourselves at the bottom of the loop, so we jump back to the top. We substitute in the current value of pin, which has a length of four. So now our loop condition is, is four less than four? Which evaluates to false. That means it's finally time to terminate the loop. We skip the loop body and look for the next line of code that's not indented inside the loop—that's our print statement.

Here we substitute in the value of pin, concatenate together, and print that sentence out to the console. That's the last line of the program, so the computer terminates execution, and we see that our loop body indeed executed four times.

More Articles

View All
Christopher Columbus part 2
Hey Becca, hey Kim. All right, so you’ve brought me here to talk about Columbus and the origins of Columbus Day. So, what’s the deal with Christopher Columbus? Was he a good guy? So, that’s a great question, Kim, and it’s something that historians and pe…
What if you were immune to chronic pain? Vaccines could make it happen. | Lou Reese | Big Think
For me, these hard problems to be able to approach them with the intention of alleviating suffering in a large patient population and globally—the opportunity to create accessible, safe, and efficacious products to go after and train, to unlock the body’s…
Interpreting equations graphically (example 2) | Mathematics III | High School Math | Khan Academy
Let F of T be ( e^{2T} - 2T^2 ) and H of T be ( 4 - 5T^2 ). The graphs of Y = F(T) and Y = H(T) are shown below. So, Y = F(T) is here in green, so this is really ( Y = e^{2T} - 2T^2 ). We see F(T) right over there, and Y = H(T) is shown in yellow. Alrigh…
Independence movements in the 20th Century | World History | Khan Academy
As we’ve seen in other videos, this is a map of the European possessions, especially the Western European possessions in much of the world. As we enter into the 20th century, before World War I, you see significant possessions by the French, not just in A…
Multiplying complex numbers graphically example: -1-i | Precalculus | Khan Academy
We are told suppose we multiply a complex number z by negative one minus i. So, this is z right over here. Which point represents the product of z and negative one minus i? Pause this video and see if you can figure that out. All right, now let’s work th…
Katy Perry - Hot N Cold (Official Music Video)
(church bell ringing) Katy, do you take Alexander to be your lawfully wedded husband? I do. Alexander, do you take Katy to be your lawfully wedded wife? (upbeat pop music) ♪ You change your mind ♪ ♪ Like a girl changes clothes ♪ ♪ Yeah, you PMS like a…