简体   繁体   中英

Why the global variable is not working in the different functions in Python?

I'm beginner in Python. I wrote the code like as below just for practice.. Please look on it

i=1
def wrte():
 global i
 while i<5:
     print "%s .Line..\n" %i
     i+=1

def appnd():
  j=i
  while i in range(i,j+3):
     print "%s .Line..\n" %i
     i+=1

def Main():
   wrte()
   appnd()

Main()

Output is like as below

  1 .Line..

    2 .Line..

    3 .Line..

    4 .Line..

**Traceback (most recent call last):
  Line 18, in <module>
    Main()
  Line 16, in Main
    appnd()
  Line 9, in appnd
    j=i
UnboundLocalError: local variable 'i' referenced before assignment**

Expected Result:: The next sequence is should be appended like

5. Line..
6. Line..
7. Line..

Please help me on this..

You need the global definition in each function in which you use that variable.

def appnd():
   global i

Note: If possible, move global variables and related functions into a class.

adding

global i

before

j=i

should solve the problem

The scope of your definitions are local. If you declare a variable as global in a function, it doesn't mean that it would be applied to all the functions. You have to declare i as global in your appnd() function too. Having said that, it doesn't mean that your style is right. You would rather pass your variables to functions.

The next definition will work:

def appnd():
  j=i
  while i in range(i,j+3):
     print "%s .Line..\n" %i

# it would print infinitely, but will work

At compile time Python looks at a way variables are used in the function to define a scope to look for them. In your definition of appnd it sees assign for i thus trying to threat it as local variable. In my code there are no assignments, so Python simply get the value for i from the parent scope - in this case i is neither local nor global, it called free variable . Execution model - Scopes and Binding - highly recommended reading.

I guess you know when you should use global, otherwise it wouldn't be in your write function. You can omit it if you only read the variable, which I think you want in your append function, but you've got an i+=1 in it, so you do modify it. Just change append to do:

for line in range(i, i + 3):
    print "%s .Line..\n" % line

In the appnd function, you must make the global variable i .

i=1
def wrte():
 global i
 while i<5:
     print "%s .Line..\n" %i
     i+=1

def appnd():
    global i
    j=i
    while i in range(i,j+3):
        print "%s .Line..\n" %i
        i+=1

def Main():
   wrte()
   appnd()

Main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM