English subtitles

← Scope Intro - Design of Computer Programs

Get Embed Code
1 Language

Showing Revision 3 created 05/24/2016 by Udacity Robot.

  1. The purpose of this segment is to talk about scope which is a concept that we've been
  2. using in the course but haven't actually talked about specifically
  3. And so if you've been getting confused by decorators which decorate decorators
  4. or functions, calling functions, return functions, and so on, this video is for you.
  5. So when we talk about a variable scope,
  6. we're talking about the region in the program in which we can access that variable.
  7. This is a concept that can go from being very simple to quite difficult.
  8. So let's start with something basic and build from there.
  9. Here we've got some very simple code, x=2, y=3, print the sum and of course, we get 5.
  10. In this example, x and y are what's called global variables
  11. and then later what we call the global environment which I'm going to represent with this box
  12. and in this environment, x is bound to the value 2 and y is bound to the value 3.
  13. The global environment is also where all our primitive operators are bound.
  14. So for example the plus sign is bound to some object which carries out addition
  15. and we won't go into too much detail about what's going on there.
  16. So let's make things a bit more interesting--so here I've just defined a function called add_nums
  17. and it returns x+y and when I run it, I get 11.
  18. So what's happened here is that our function has created a new scope
  19. and this scope is local to the function and so what happened when we defined add_nums
  20. was we made this binding between this name and the function object.
  21. Now that's fine but as soon as we call add_nums by saying
  22. print the result print add_nums, we created a new environment
  23. Now I'm going to call this environment add_nums, and in this environment, we made an assignment.
  24. There are two assignment from x to 5 and from y to 6
  25. and when we call add_nums, Python prefers to choose variables within its local scope.
  26. If it can do that, it then moves up following this pointer
  27. to what's called its enclosing environment since this add_nums environment
  28. lives inside of this global environment and lives there.
  29. If after following all these paths up into the global environment, it still doesn't find
  30. the variable it's looking for that's when we get an error-- specifically a name error.