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关键字。


目录
相关文章
|
10月前
variable `xxx' has initializer but incomplete type的解决方法
variable `xxx' has initializer but incomplete type的解决方法
153 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
410 0
|
5月前
Error: Plugin/Preset files are not allowed to export objects, only functions……
Error: Plugin/Preset files are not allowed to export objects, only functions……
|
9月前
UnboundLocalError: local variable ‘loss’ referenced before assignment解决方法
UnboundLocalError: local variable ‘loss’ referenced before assignment解决方法
154 0
对‘avformat_find_stream_info’未定义的引用、to the PKG_CONFIG_PATH environment variable
对‘avformat_find_stream_info’未定义的引用、to the PKG_CONFIG_PATH environment variable
64 0
解决办法:defined but not used [-Werror=unused-variable]
解决办法:defined but not used [-Werror=unused-variable]
593 0
|
Java
The type XXX cannot be resolved. It is indirectly referenced from required .class files
The type XXX cannot be resolved. It is indirectly referenced from required .class files
85 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
50 0
Unexpected aliasing of ‘this‘ to local variable.
Unexpected aliasing of ‘this‘ to local variable.
1258 0
Unexpected aliasing of ‘this‘ to local variable.