local variable 'xxx' referenced before assignment

简介: 定义了一个全局变量 s ,Python的一个函数里面引用这个变量,并改变它的值,结果报错local variable 'xxx' referenced before assignment,代码如下:s = 2  def fun():       if s== 2:          print s        s= 3         错误的意思就是s这个变量在引用前还没有定义,这上面不是定义了么?但是后来我把s= 2这句去掉就好了。

定义了一个全局变量 s ,Python的一个函数里面引用这个变量,并改变它的值,

结果报错local variable 'xxx' referenced before assignment,

代码如下:

  1. s = 2  

  2. def fun():   

  3.     if s== 2:  

  4.         print s

  5.         s= 3 

  6.   


      错误的意思就是s这个变量在引用前还没有定义,这上面不是定义了么?但是后来我把s= 2这句去掉就好了。后来想起python中有个global关键字是用来引用全局变量的


  1. s = 2  

  2. def fun():   

  3.      golbal s

  4.     if s== 2:  

  5.         print s

  6.         s= 3 

  7.         print s

原来在python的函数中和全局同名的变量,如果你有修改变量的值就会变成局部变量,在修改之前对该变量的引用自然就会出现没定义这样的错误了,如果确定要引用全局变量,并且要对它修改,必须加上global关键字。


目录
相关文章
variable `xxx' has initializer but incomplete type的解决方法
variable `xxx' has initializer but incomplete type的解决方法
361 0
undefined reference to symbol 'dlsym@@GLIBC_2.17' libdl.so: error adding symbols: DSO missing from c
undefined reference to symbol 'dlsym@@GLIBC_2.17' libdl.so: error adding symbols: DSO missing from c
589 0
|
4月前
|
Java Maven
The JAVA_HOME environment variable is not defined correctly,this environment variable is needed to
The JAVA_HOME environment variable is not defined correctly,this environment variable is needed to
UnboundLocalError: local variable ‘loss’ referenced before assignment解决方法
UnboundLocalError: local variable ‘loss’ referenced before assignment解决方法
232 0
解决办法:defined but not used [-Werror=unused-variable]
解决办法:defined but not used [-Werror=unused-variable]
785 0
Duplicate methods named spliterator with the parameters () and () are inherited from the types Colle
Duplicate methods named spliterator with the parameters () and () are inherited from the types Colle
74 0
Unexpected aliasing of ‘this‘ to local variable.
Unexpected aliasing of ‘this‘ to local variable.
1414 0
Unexpected aliasing of ‘this‘ to local variable.
MGA (Managed Global Area) Reference Note (Doc ID 2638904.1)
MGA (Managed Global Area) Reference Note (Doc ID 2638904.1)
326 0