Environment Diagrams Quick Review

Environment Diagram = A cool way to diagram a function and understand what the function is actually doing

why environment diagrams?

At first environment diagrams can be kind of confusing and weird. I mean, why do I have to sit here and diagram these functions, when I already know how to write functions? How is this even supposed to help me?

Well, first off, no matter how good you are at programming, it always helps to be able to diagram what you are doing, and make sure that you are writing the correct code. This class ramps up very quickly, and having some way to check your work and make sure you really understand what’s going on is super helpful. Plus, the great thing about environment diagrams is, as opposed to writing code, which takes a lot of intuition, writing out an environment diagram is very formulaic and just requires you to be able to follow a set of steps. Remember this: the rules of environment diagrams will never change throughout the semester; we may add in some new rules, but the old ones will always stay the same.


the 12 rules of environment diagrams

  1. Any code not in a function is in what is called “the global frame”

  2. When defining a variable, you fill in its value in a box beside its name

  3. When defining a function, draw an arrow to the function name, parameters, and parent frame

  4. The parent frame will always be the frame that the function was defined in

  5. For any assignment statements a = b, you take the value in b’s box and put it in a’s box

  6. Whenever you call a function, open a new frame and write in the name of the function and the parent frame, unless the function is built in (like add, max, etc.)

  7. If the function is built in, do not open a new frame, just write in the function’s return value (ex: x = max(2, 3), just write x = 3)

  8. The first thing defined in any frame are the parameters of the frame’s function (if there are any)

  9. Whenever you define a new variable or function in your current function, add that variable/function and its value to the current frame in your diagram

  10. Whenever you are using any variable in your code, Python will first check for its value in the current frame, then, in the parent frame, then the parent’s parent and so on until it reaches the global frame, at which point it will error if it doesn’t find the variable

  11. A frame is only closed (or finished) when something has been returned or when there are no more lines to be executed

  12. If the function ends without returning anything, the return value is None