This question has already been answered:

Please tell me how the reserved word "global" works in Python

Reported as a duplicate at MaxU. python Mar 17 at 10:07 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    2 answers 2

    When creating a new variable in a function, they act only in the limit of the function. To change global variables inside a function, define them with global. (An example is the answer above)

      When new variables are created inside a function, they have a local scope. That is, such variables are defined only within the function body, and they are destroyed when the function returns control to the caller. To be able to change global variables inside a function, these variables should be defined in the function body using the global statement.

      count = 0 ... def foo(): global count count += 1 # Изменяет значение глобальной переменной count 
      • How to use the "global" - Alexey
      • @ Alexey, it would be more correct not to use it at all. See the remark at the end of this answer - MaxU
      • @MaxU, I would not say. Sometimes it's hard to do without global. In some complex functions, especially with cycles if. - m0nte-cr1st0
      • Thank you very much - Alexey