Advertisement
wagner-cipriano

python variables and scope

Oct 12th, 2016
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.84 KB | None | 0 0
  1. #Ref: stackoverflow.com/questions/1261875/python-nonlocal-statement
  2. from __future__ import print_function      #Compatibilidade func print python 2/3
  3.  
  4. global x #OPC -> main
  5. x = 0
  6.  
  7. def fext():
  8.     x = 1
  9.     def fin_nl():
  10.         #Var nao local da funcao interna, pega da func externa (fext)
  11.         nonlocal x
  12.         x = 2
  13.         print("fin_nl: ", x)
  14.        
  15.     def fin_l():
  16.         #Variavel local
  17.         x = 3
  18.         print("fin_l:  ", x)
  19.        
  20.     fin_nl()
  21.     fin_l()
  22.     print("fext:   ", x)
  23. #
  24.    
  25. def f_varg():
  26.     #Variavel global
  27.     global x
  28.     x = 4
  29.     print("f_varg: ", x)
  30. #
  31.  
  32. #MAIN    
  33. fext()
  34. print("main:   ", x)
  35. f_varg()
  36. print("main:   ", x)
  37.  
  38.  
  39. """
  40. ANTES DE EXECUTAR O CÓDIGO,
  41. Preencher abaixo os valores que serão impressos  
  42. fin_nl: x
  43. fin_l:  x
  44. fext:   x
  45. main:   x
  46. f_varg: x
  47. main:   x
  48. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement