reading-notes

reading notes for code fellows


Project maintained by dLeigh01 Hosted on GitHub Pages — Theme by mattgraham

Ten Thousand 2

Being able to maniuplate when and where variables will be effective will be an important tool in building a more complicated application than we have been so far, such as wiht the Ten-Thousand Game.

Python Scope

Python scope is generally presented using LEGB (Local, Enclosing, Global, and Built-In). Globally scoped variables are available to all your code, while locally scoped variables are only visible to other pieces of code within the same scope as them. Local scope is the code block or body of any python function, enclosing(non-local) scope exists only in nested functions, in which case the enclosing scope is the scope of the outer function, global scope is everything at the top level in a python program, and built-in scope contains things like keywords and exceptions, things built into the python language. Python uses this order to look up names, so if ou have something like a local name that is the same as a global name, it will take the local value as the first instance it finds.

If you want to update a global variable within a local environment, you can use a global statement, which will map all variable names following it within the local scope. Similarly, a nonlocal statement can be used to define a list of names to be treated as nonlocal within an inner function.

Things I Want to Know More About

Discussion

I’d used global before during my work on sololearn when I was having trouble getting an end of lesson project to work; it’s very interesting now seeing a bit more of the reasoning behind why I needed it and how it was working besides what I knew when I found it, which was just ‘python dislikes global variables, this makes it usable, carry on.’

[< table of contents]

[< home]