-2

Here i have a code of python. In this code i define two function and at top one variable a i have created. but when i try to call a in local function with assigning statement below it generate error that local variable not initialized. if i didn't assign it value than it access value of successfully.

 a=5
 def local():
     print("inside local Function before changing %d"%a)
     a=3
     print("Insie local Function after changing %d"%a)
 local()
 print("outside local Function after changing %d"%a)
 def global_ars():
     global a
     a=6
     print("Inside Global Function %d"%a)
global_ars()
print("outside Global Function %d"%a)

i want to know how can i access to global value and can assign new value but only at local level not on global level.

  • If you google python 3 + the error message from your code the top entry (for me) is http://stackoverflow.com/q/10851906/1144523 – machow Jul 11 '14 at 00:35

2 Answers2

0

Assuming you want to start with the global value, but have assignments only affect a local copy, the solution is to just make another variable:

def f():
    local_a = a
    # Now use local_a instead of a.

If you want assignments inside the function to affect the global variable, use global, like you're already doing.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

Simply get the value from the global scope and don't modify the global variable:

a = 0
def global_fn():
    global a
    local_a = a
    print("local original %d"%local_a)
    local_a = 10
    print("local modified %d"%local_a)
 global_fn()
 print("global unmodified %d"%a)
zambotn
  • 735
  • 1
  • 7
  • 20