Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

Python global/local variables

Why does this code work:

var = 0

def func(num):
    print num
    var = 1
    if num != 0:
        func(num-1)

func(10)

but this one gives a "local variable 'var' referenced before assignment" error:

var = 0

def func(num):
    print num
    var = var
    if num != 0:
        func(num-1)

func(10)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because in the first code, you have created a local variable var and used its value, whereas in the 2nd code, you are using the local variable var, without defining it.

So, if you want to make your 2nd function work, you need to declare : -

global var

in the function before using var.

def func(num):
    print num
    var = 1  <--  # You create a local variable
    if num != 0:
        func(num-1)

Whereas in this code:

def func(num):
    print num
    var = var <--- # You are using the local variable on RHS without defining it
    if num != 0:
        func(num-1)

UPDATE: -

However, as per @Tim's comment, you should not use a global variable inside your functions. Rather deifine your variable before using it, to use it in local scope. Generally, you should try to limit the scope of your variables to local, and even in local namespace limit the scope of local variables, because that way your code will be easier to understand.

The more you increase the scope of your variables, the more are the chances of getting it used by the outside source, where it is not needed to be used.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...