On 04/08/2020 20:38, Steve wrote:
Why should line 6 fail until line 7 is commented out?
Python complains that MSN is "referenced before assignment".

def ReadTheEQfile():
   global MSN
   MSN = ("1 Monitor") #This line works every time.
def EditTheEQlist():
   print("MSN2 = " + MSN) # Works if the next line is commented out.
   MSN = ("3 Monitor")
# Main()
ReadTheEQfile()
print("MSN1 = " + MSN) # This line works every time
EditTheEQlist()

NB there are no lineNRs above!
(added comment/guide == good job!)


Others have answered the question. Here is some reading to consolidate your understanding:-

What are the rules for local and global variables in Python?
https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

Assignment is defined recursively depending on the form of the target (list). When a target is part of a mutable object (an attribute reference, subscription or slicing), the mutable object must ultimately perform the assignment and decide about its validity, and may raise an exception if the assignment is unacceptable. The rules observed by various types and the exceptions raised are given with the definition of the object types (see section The standard type hierarchy).
...
If the target is an identifier (name):

If the name does not occur in a global or nonlocal statement in the current code block: the name is bound to the object in the current local namespace.

Otherwise: the name is bound to the object in the global namespace or the outer namespace determined by nonlocal, respectively.
https://docs.python.org/3/reference/simple_stmts.html#assignment-statements

...we have the function modifying x. It may appear somewhat confusing since x is being used in multiple locations...
https://pythonprogramming.net/global-local-variables/

"Scope", particularly in its applications to Classes and Namespaces:
https://docs.python.org/3/tutorial/classes.html

The "LEGB" 'rule' (NB not a term you'll find in the Python docs) ie Local, Enclosing, Global, and Built-in scopes:
https://realpython.com/python-scope-legb-rule/
and more in:
https://realpython.com/python-namespaces-scope/
--
Regards =dn
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to