Why in the last print x = 2?

def func_outer(): x = 2 print('x равно', x) def func_inner(): global x x = 5 print (x) func_inner() print('Локальное x сменилось на', x) func_outer() 
  • five
    global x -> nonlocal x :) - gil9red
  • I know that. I want to understand why global works like this. And I do not fully understand how nonlocal works, please explain too, if not difficult. - Decya
  • As I understand it, after the definition in the nested function, x should be equal to 5 and outside the nested function. Or will x be equal to 5 only in the body of the second function and all nested in it? I understood correctly? - Decya
  • I understand how they work. - Decya
  • Oh, you are well done, that figured out :) Write in the answer about this;) - gil9red

1 answer 1

For example, you have two functions, one of which is nested in the second. If you want to get the value of a variable from the first function in the second function, then in the second function you need to specify nonlocal to the variable that you want to pass. x (1) is the first function, x (2). Suppose that we have x (1) equal to 5. We specified nonlocal x (2), so x (1) will be equal to 5 in the second function until we rewrite this variable. It will be the same if we create another nested function to which we also want to pass this variable.

 def func_outer(): x = 2 print('x равно', x) def func_inner(): nonlocal x print (x) x = 5 print (x) def func_three(): nonlocal x print ('До изменения третьей', x) x = 9 print('Чекаю третью после изменения', x) func_three() func_inner() print('Локальное x сменилось на', x) func_outer() 

As for global. There is a similar situation. But in this case we can transfer to a function or class, the value of a variable outside the body of a class or function.

 global x x = 2 def func_outer(): #x = 2 print('x равно', x) def func_inner(x): #nonlocal x print (x) x = 5 print (x) def func_three(x): #nonlocal x print ('До изменения третьей', x) x = 9 print('Чекаю третью после изменения', x) func_three(x) func_inner(x) print('Локальное x сменилось на', x) func_outer() 
  • global not used outside functions. To use it in the methods, it seems to me, is also such an idea. - Sour Sourse
  • Not understood. Why then use it? Isn't that what the global function is all about? - Decya
  • To include an object from globals() in the function namespace, and use it. Eliminates the name conflict situation. - Sour Sourse 5:28 pm
  • Here are the links Of1 , Of2 , ru SO . - Sour Sourse 5:42 pm