我不明白这个error=UnboundLocalError:赋值前引用的局部变量'overWrite'

2024-04-26 13:09:14 发布

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

如果你能帮我找出这个错误发生的原因,那将非常有帮助 作为一个初学者,我学习代码的速度很慢,所以不要以此来评判我:)

import os
overWrite = ""


def filecheck():

    garry = ("i love this leason")

    filename1 = input("please enter a name : ")
    filename = filename1 + ".txt"

    dave = os.path.isfile(filename)

    if dave == False:
        print("you can have this name")
    else:
        overWrite = input(" do you want to overwrite this file : ")

    if overWrite == "yes":
        with open(filename)as f:
            f.write = (garry)

    else:
        filecheck()

filecheck()


please enter a name : ggggggg
you can have this name
Traceback (most recent call last):
  File "F:/computer science/dictionary test.py", line 26, in <module>
    filecheck()
  File "F:/computer science/dictionary test.py", line 19, in filecheck
    if overWrite == "yes":
UnboundLocalError: local variable 'overWrite' referenced before assignment

Tags: nameyouinputifosfilenamethiscan
1条回答
网友
1楼 · 发布于 2024-04-26 13:09:14

这是因为您引用了此行中的变量overwrite

if overWrite == "yes":

在函数中给定一个值之前。Python首先查看函数的作用域,因此您需要告诉它,当它看到overwrite时,它应该查看全局变量overwrite,或者您需要重构代码。可以使用global关键字在函数中将变量声明为全局变量,如下所示:

def filecheck():
    global overwrite
    garry = ("i love this leason")

    filename1 = input("please enter a name : ")
    filename = filename1 + ".txt"
    ...

Here's the link介绍一下python文档中的局部变量和全局变量。你知道吗

相关问题 更多 >