Avatar ·

Why is the global variable inaccessible from the function?

📁 функция, python, ии

Please tell me why the function does not display the value of s

  S =  "" I'M Global Variable ""    def   foo  ():   print  (s) r =  '' reset global Variable ' foo ()     

I assumed that when the interpreter reaches the Print (S) line, it will understand that in the field of visibility of the FOO function there is no such variable. Therefore, it will begin to look for it in the exteal area of ​​visibility, but there is it.

However, as a result, the following error message is displayed in the console:

  Traceback (Most Recent Call Last):  File , line  7 ,  in  & lt; moodule & gt;  foo ()  file  "" index.py "" , line  4 ,  in  foo  print  (s) unboundLoCaleror: Local Variable  'S'  refereNCED Before Assignment    

The problem disappears if the line

  S =  'Reset Global Variable'      

But I still do not understand the mechanism