Hello, I get acquainted with python and after c ++ I categorically do not understand the principle of using global variables. If a variable located in def specify global, is it possible for me to use its value outside this function, I just can't do it. Maybe just because I'm new and the obvious things are still too complicated for me.

def check(): global urokb_in urokb_in = 1 with open('users.txt', 'r') as f: line = f.readline() f.close() with open('progress.txt', 'r') as k: while True: global uroka_in lines = k.readline() if line == lines.rstrip(): uroka_in = int(k.readline().rstrip()) urokb_in = uroka_in + 1 uroka_str = str(uroka_in) urokb_str = str(urokb_in) lines.replace(uroka_str, urokb_str) k.close() break if not lines: k.close() urokb_in = 1 with open('progress.txt', 'a') as j: j.write(line) j.write('\n') j.write(str(urokb_in)) j.write('\n') j.close() break if urokb_in == 1: educate__scr = PhotoImage(file='e_scr_1.png') educate_label = Label(root, image=educate__scr) educate_label.place(x=0, y=0) 

More experienced coders tell me how to fix it. SyntaxError: name 'urokb_in' is used prior to global declaration

  • global uroka_in must be inside a function (immediately after def , only once). - insolor
  • Possible duplicate question: Error with global variable? - insolor
  • @insolor then I cannot use the value of urokb_in in the condition outside the function - Andrei Grivkin
  • You can. You just function is not called, as I understand it. You must first call the function, and then check the condition. - insolor
  • @insolor def chek is called earlier by pressing a button. And when I exit the function, I want to get the value from urokb_in - Andrew Grivkin

3 answers 3

If you do not specify global or nonlocal, then x = within the function creates a local variable .

If you want to create a new global variable / or override the old one inside the function (not at the global level), then you can use global. This can be useful when working with the multiprocessing module to inherit the desired global variables from the parent process:

 def init(shared_arr_): global shared_arr shared_arr = shared_arr_ # must be inherited, not passed as an argument 

Full code example .

If you just want to use an existing global variable without overriding it, then global is not needed (otherwise, for example, each function would have to have each module used, each global function be declared global).

I am new and the obvious things are too complicated for me

For beginners: do not override global variables at all , that is, avoid global . Consider each appearance of global in code as an error if there are no special reasons for using this construct (as in the example with multiprocessing ). If you can’t get rid of global, then create a minimal code sample and ask a separate question: "how to get rid of global by doing X"

  • How to locally assign a global variable value? I created a local variable with the same name. well, except nonlocal =) - eri
  • @eri look at shared_arr in the example code above. What behavior did you expect and what happens instead? - jfs

The global used where it is necessary to explicitly indicate that an object from the global scope should be used (module namespace or the globals dictionary) and cancels the standard search mechanism for a variable ( LEGB ), in addition, it makes it possible to change the object out of its scope. It requires discipline in general, because if, before a global a declaration in a nested scope, a name was not in OB globals() it will be created during the first assignment operation and will not disappear when the work is completed (for example, a function).

 dir() # ['__builtins__'] def foo(): global a a = 22 pass dir() # ['__builtins__', 'foo'] # foo необходимо вызвать. foo() dir() # ['__builtins__', 'a', 'foo'] a # 22 # а теперь живет в globals() def foo1(): print(a) foo1() # 22 # по правилу LEGB имя а было найдено в globals() def foo2(): a += 4 pass foo2() # Traceback (most recent call last): # File "<input>", line 1, in <module> # File "<input>", line 2, in foo2 # UnboundLocalError: local variable 'a' referenced before assignment # запрещено изменение переменных не в своей области видимости для этого # требуется сначала указать что нужно изменить именно a из globals() def foo3(): global a a += 4 foo3() a # 26 
  • Tell me how to intercept urokb_in after if not lines and after if line == lines.rstrip (): - Andrew Grivkin

The global variable must be specified directly in the function body at the very beginning, for example:

 x = 1 def set_value(): global x x = 2 print(x) >>> 1 set_value() print(x) >>> 2