Feb-24-2022, 06:03 PM
(This post was last modified: Feb-24-2022, 06:08 PM by deanhystad.)
When assigning a variable Python uses local scope unless otherwise directed.
By default, assignment is to variables in the current (local) scope. You can use the global keyword to tell Python to assign a variable in the global scope instead of the local scope.
You can see variables that exist in surrounding scopes, but this does not override the "assign to local behavior". In your first post sample_fcn could print the global check, but it could not assign a new value to the global check.
check = 1This code assigns 1 to the variable "check" in the local scope. If the variable does not exist it is created. If this code executes in global/module scope it creates a global variable. If it is executed inside a function it creates a local/function variable.
By default, assignment is to variables in the current (local) scope. You can use the global keyword to tell Python to assign a variable in the global scope instead of the local scope.
You can see variables that exist in surrounding scopes, but this does not override the "assign to local behavior". In your first post sample_fcn could print the global check, but it could not assign a new value to the global check.
check = 0 def sample_fcn(): print(check) # This would see the global variable check because Global scope surrounds Local scope (LEGB) def other_fcn(): check = 1 # This creates a local variable check def and_another_fcn(): global check # This tells Python to use check from Global scope check = 1 # Sets value of check in Global scopeYour function raised an exception when it did the "check += 1" which expands to
check = check + 1The "check =" creates a local, undefined variable named check. The "check + 1" tries to add one to the undefined check. When getting a value for check Python does not look at the global check because it found check in the local scope.