我不能在函数外使用局部变量



我正在尝试从一个代码导入函数到另一个,第一个程序正在执行。txt文件并搜索是否存在word:

exists = 0 #To import this variable to other code i have to this
path = 'D:Pythondatabase.txt'
def search(search_word):
file = open(path)
strings = file.read()
if(search_word in strings):
exists = 1
else:
exists = 0

其他代码:

word = input("Enter one word: ")
search(word)
if exists == 1:
print("This word exists in database!")
else:
print("This word doesn't exist in database!")

即使这个词在数据库中,程序也会打印"这个词在数据库中不存在"。问题是,我不能更新局部变量存在于函数搜索。我尝试使用全局存在,它不工作!请帮助!

可以让search函数返回该值

def search(search_word):
file = open(path)
strings = file.read()
if(search_word in strings):
return 1
else:
return 0
word = input("Enter one word: ")
exists = search(word)
if exists == 1:
print("This word exists in database!")
else:
print("This word doesn't exist in database!")

这是因为你又在函数范围内定义了exists

试试这个:

path = 'D:Pythondatabase.txt'
def search(search_word):
file = open(path)
strings = file.read()
if(search_word in strings):
exists = 1
else:
exists = 0
return exists

,

word = input("Enter one word: ")
exists = search(word)
if exists == 1:
print("This word exists in database!")
else:
print("This word doesn't exist in database!")

现在您的函数只是将变量exists设置为1或0。exists局部变量。根据定义,应该而不是可以从其他地方访问它。如果你想知道值,你需要加上return。

path = 'D:Pythondatabase.txt'
def search(search_word):
file = open(path)
strings = file.read()
if(search_word in strings):
return 1
else:
return 0

添加return后,需要在某处接收值。您可以按照其他评论中的建议进行操作,并将其保存到变量exists中,或者您可以按照我下面的建议进行操作。由于您将使用结果作为if-else来检查返回值是0还是1,因此您可以立即检查if (search(word)):以获得更清晰的代码。

def main():
word = input("Enter one word: ")
if search(word):
print("This word exists in database!")
else:
print("This word doesn't exist in database!")
if __name__ == "__main__":
main()

最新更新