2016-02-19 57 views
0

之前引用如果你能帮助我找出为什么这个错误发生会如此有益 ,我学习码慢慢作为一个初学者所以尝试不能判断我在这个:)我不明白这个错误= UnboundLocalError:局部变量“覆盖”分配

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 

回答

0

这是因为你在这一行

if overWrite == "yes": 

引用变量overwrite之前,它必然给该函数的值。看起来的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到一些关于当地VS在Python文档的全局变量。

相关问题