python 我不能在函数外使用局部变量[duplicate]

mmvthczy  于 2022-12-25  发布在  Python
关注(0)|答案(3)|浏览(141)
    • 此问题在此处已有答案**:

How do I get a result (output) from a function? How can I use the result later?(4个答案)
6个月前关闭。
我试图从一个代码导入到另一个函数,第一个程序正在执行. txt文件,并搜索是否存在的话:

exists = 0 #To import this variable to other code i have to this

path = 'D:\Python\database.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!")

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

jum4pzuy

jum4pzuy1#

您可以让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!")
htrmnn0y

htrmnn0y2#

因为你又在函数作用域中定义了exists。
试试这个:

path = 'D:\Python\database.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!")
goqiplq2

goqiplq23#

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

path = 'D:\Python\database.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来检查return是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()

相关问题