Get The Full “Learn Python 🐍” Online Course:
The following video is from an online educational course produced by Mnemonic Academy that teaches the basics of Python programming using mnemonics, metaphors and the science of learning titled “Learn Python: Like a Bee Student”, taught by instructor Dylan Jorgensen
What is scope? Variable scope?
- When a variable is used in a code block, that variable may or may not have permission to be used outside of the code block.
- So scope identifies the boundaries that a variable can found within.
- Scope errors cause a “NameError”
What defines the rules of Scope? LEGB rules?
- There is a concise set of rules that can be summarized in the acronym LEGB.
- L. is Local — Variables assigned in any way within a function, and not declared global in that function.
- E. is Enclosing — Variables in the local scope of any and all enclosing nesting functions, from inner to outer.
- G. is Global (module) — Variables assigned at the top-level of a module file, or declared global.
- B. is Built-in (Python) — Variables preassigned in the built-in names module. Examples are: open, range & SyntaxError.
What's the difference between a variable's scope and a variable's lifetime?
- Because all variables are going to go through a process of mutability and evolving over time, the variable’s lifetime is a reference to points in the lifetime.
- Like in our penguin example this would be the difference between a baby penguin and a teenager penguin. Independent of which exhibit the penguin is found in, inside of our zoo.
"Names" and "binding" vs. "variables" and "assignment"?
- In this course we are going to stick to variables and assignments. But some day you might run into the coding equivalent of the grammar police, who will lecture you on how it’s better to think of variables as names; and assignments as bindings.
- And when that day comes just acknowledge that he or she was probably…