首页 > 解决方案 > 为什么这个变量不是全局的(不能在函数中使用)?

问题描述

我知道我必须使用global关键字来访问变量,但我的问题是为什么它不能在函数中使用?

source = "C:/ALL IN ONE/Test File"
temp = "C:/ALL IN ONE/Temp Folder"
num_files = 0

def sort():
    if not os.path.exists(temp):
        os.makedirs(temp)
        
    for folder_path, folder, files in os.walk(source):
        for file in files:
            num_files += 1   # I can't seem to access the variable "num_files" outside the function
            if file.endswith("txt"):
                pass

标签: python

解决方案


global在函数中定义变量,如下所示:

num_files = 0

def sort():
    global num_files
    # rest of your code

在没有将其声明为全局的情况下,要执行num_files += 1基本上是num_files = num_files + 1,该函数会搜索已初始化局部变量的声明num_files以访问其赋值右侧的值,但没有任何值,因此会引发UnboundLocalError: local variable referenced before assignment异常。

请参阅文档


推荐阅读