python: local variable 'xxx' referenced before assignment

简介:

阅读目录

问题发现

复制代码
xxx = 23
def PrintFileName(strFileName): 
    if xxx == 23:
        print strFileName
        xxx = 24

PrintFileName("file")
复制代码

报错

复制代码
Traceback (most recent call last):
  File "C:/Users/Desktop/del.py", line 7, in <module>
    PrintFileName("file")
  File "C:/Users/jihite/Desktop/del.py", line 3, in PrintFileName
    if xxx == 23:
UnboundLocalError: local variable 'xxx' referenced before assignment
复制代码

意思说局部变量‘xxx’前边没有定义,但是最前面不是定义了吗。注意这里提示是局部变量,一开始定义的为全局变量。如果这里定义的就是全局变量可以通过关键字global来说明

复制代码
xxx = 23
def PrintFileName(strFileName): 
    if xxx == 23:
        global xxx
        print strFileName
        xxx = 24

PrintFileName("file")
复制代码

运行正常。

但是这样也是没错

复制代码
xxx = 23
def PrintFileName(strFileName): 
    if xxx == 23:
        print xxx

PrintFileName("file")
复制代码

问题所在

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

 





本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/4764078.html,如需转载请自行联系原作者


相关文章
|
2月前
|
JavaScript 前端开发 Python
成功解决:Can‘t find Python executable “python“, you can set the PYTHON env variable.
这篇文章分享了作者在运行前端Vue项目时遇到的关于Python执行环境的问题和解决方法。问题是由于找不到Python可执行文件导致的编译错误,解决方法包括安装编译环境、卸载并重新安装出现问题的`node-sass`包,并重新执行`npm install`和`npm run dev`。
成功解决:Can‘t find Python executable “python“, you can set the PYTHON env variable.
|
4月前
|
Python
Python Tkinter之variable用法
Python Tkinter之variable用法
80 3
|
4月前
|
Python
python中可变参数(Variable Arguments)
【6月更文挑战第10天】
21 1
|
3月前
|
程序员 Python
【Python】已解决:SyntaxError: expression cannot contain assignment, perhaps you meant “==“?
【Python】已解决:SyntaxError: expression cannot contain assignment, perhaps you meant “==“?
42 0
|
3月前
|
Python
安装 supervisor报错执行python setup.py install时No local packages or working download links found for meld3
安装 supervisor报错执行python setup.py install时No local packages or working download links found for meld3
25 0
|
5月前
|
Python
gyp ERR! stack Error: Can‘t find Python executable “python“, you can set the PYTHON env variable.
gyp ERR! stack Error: Can‘t find Python executable “python“, you can set the PYTHON env variable.
138 1
|
5月前
|
存储 安全 Python
什么是Python中的线程局部存储(Thread Local Storage)?
【2月更文挑战第3天】【2月更文挑战第6篇】
121 0
|
存储 传感器 Python
[oeasy]python0132_变量含义_meaning_声明_declaration_赋值_assignment
[oeasy]python0132_变量含义_meaning_声明_declaration_赋值_assignment
90 0
[oeasy]python0132_变量含义_meaning_声明_declaration_赋值_assignment
|
存储 Python
Python threading Local()函数用法:返回线程局部
Python threading Local()函数用法:返回线程局部
下一篇
无影云桌面