Now that we know how to start basic coding, we should also look into how we can visualize our code. On a large scale, this is relatively hard to do as the project gets too big to visualize. However, when first learning how to program, it can be extremely useful to visualize your code and how it runs.
Environment diagrams are visualizations of your code that are generated as you progress through a program. It documents the status of each variable in each frame, and it documents the status of each frame that’s created by a function. It’s quite useful for this class, actually, for you to understand a little bit of how Python works under the hood.
This course uses the style of diagrams generated by PythonTutor, which I think is a very easy-to-read style. When you write and execute code, you can step through it line by line and the current state of the environment will be shown to you on the right side.
The global frame in the environment diagram is where your program begins. All functions you define and all variables created outside of functions are said to be within this frame. See this PythonTutor diagram for an example. Every time you update a variable, you simply replace its value in the diagram. In the previous demo, click “Next” and see what happens to the value of
Every time you execute a function, a new frame is created. This new frame contains all the variables created inside it. Note that a new frame is not created every time a function is created, only when it is called and executed. Hit next again on that demo. You’ll notice that a new frame will be created, called
y. If you hit next again, the variable
z will be created within this new frame. Each function’s frame will also include its return value when you get to it. When the function is done, you’ll notice that the frame disappears. Don’t be fooled though – the frame doesn’t necessarily become irrelevant, as you’ll see very soon.
That’s a very brief introduction to environment diagrams; they help you keep track of your variables and functions. This is just the first week, so you won’t see too much going on. However, as you progress throughout the course, you’ll see why environment diagrams can be particularly useful in stepping through your code.