Thursday, February 27, 2014

Week 5 - More Recursion and Namespaces

In our lectures this week, we wrote out code for the recursive solution to the Tower of Hanoi problem, for three stools and any amount of cheeses.  This in-class exercise was great for making sure that I understood how to approach a problem recursively, as well as being an important piece of the Tour.py file we needed to write for Assignment 1.

We also covered Namespaces and Scope this week.  Basically, when an object is created, the name assigned to that object is only valid in the namespace in which it was created.  For example, say we create a variable x within a function test().  Variable x can be used anywhere inside the scope of function test(), but outside of that function, x does not exist.  As a matter of fact, the outside of test() can have its own variable called x, which is completely independent of the x in test().

There are multiple levels of scopes that Python handles, from innermost to outermost:
  • The local scope, which is the "current" function
  • The nonlocal scope, which is the outer functions, if any, of a function.
  • The global scope, which is the module, __main__
  • The outermost scope, which has all of Python's built-in names.
In order to rebind an object, the "nonlocal" or "global" statements can be used.  However, using global variables is not recommended, as they can be difficult to deal with and may easily lead to unexpected behaviour, and from the examples I have looked at, it is pretty easy to understand why they aren't the most intuitive thing to work with.

No comments:

Post a Comment