Function with variable scope

  Local variables and global variables and closure variables (variables interposed therebetween)

  global Keywords: Change the local area globals (function can only be read by default global variables can not be modified)

  nonlocal Keywords: nested function modified closure variables (variables defined outer function corresponding to a global variable which statement blocks)

  

. 1 I. 1 =
 2 J = 2
 . 3  Print ( ' global variables: = I ' , I, ' J = ' , J)
 . 4  
. 5  DEF Fun ():
 . 6      Global I, J # in order to modify global variables need to use a global keyword to prior declaration 
. 7      I = 2
 . 8      J =. 3
 . 9  
10  Fun ()
 . 11  Print ( ' call fun, the global variable modifications: = I ' , I, ' , = J ' , J)
 12 is  
13 is  
14  DEF fun1 ():
 15      I = 0
16      Print ( ' I = ' + STR (I) + ' , in fun1, the local variable ' )
 . 17  
18 is  fun1 ()
 . 19  Print ( ' I = ' + STR (I) + ' , the external function is globally variable ' )
 20 is  
21 is  
22 is  DEF fun2 ():
 23 is      K = 2   # K is a variable closure (Closue), ranging between global and local variables, and modified using nonlocal keyword to modify the first statement when 
24      DEF FUN3 ():
 25          nonlocal K
 26 is          K. 3 =
 27          A = K + I
 28          returnA
 29      Print ( ' fun2, the closure variables = K ' + STR (K))
 30      return FUN3 ()
 31 is  
32  Print (fun2 ())

 

Guess you like

Origin www.cnblogs.com/guoyujiang/p/11595011.html