为什么pycharm警告“上面定义的重新声明的变量没有使用”?

2024-04-26 07:26:45 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么PyCharm在下面的代码中警告我Redeclared 'do_once' defined above without usage?(警告在第3行)

for filename in glob.glob(os.path.join(path, '*.'+filetype)):
    with open(filename, "r", encoding="utf-8") as file:
        do_once = 0
        for line in file:
            if 'this_text' in line:
                if do_once == 0:
                    //do stuff
                    do_once = 1
                //some other stuff because of 'this text'
            elif 'that_text' in line and do_once == 0:
                //do stuff
                do_once = 1

因为我希望它对每个文件都做一次,所以每次打开一个新文件时,它都会像我希望的那样工作,但由于我没有学习过python,只是通过做和google学习了一些东西,我想知道为什么它会给我一个警告,以及我应该做什么不同的事情。在

编辑: 尝试使用布尔值,但仍然收到警告:

为我重现警告的简短代码:

^{pr2}$

Tags: path代码textin警告forifline
2条回答

我的猜测是PyCharm被使用整数作为标志混淆了,在您的用例中可以使用几种替代方法。在

使用布尔标志而不是整数

file_processed = False
for line in file:
    if 'this' in line and not file_processed:
        # do stuff
        file_processed = True
    ...

更好的方法是在处理完文件中的某些内容后立即停止跳转,例如:

^{pr2}$

为了解决一般情况:

你可能在做什么

v1 = []
for i in range(n):
    v1.append([randrange(10)])

v2 = []
for i in range(n):      # <<< Redeclared i without usage
    v2.append([randrange(10)])

你能做什么

^{pr2}$

相关问题 更多 >