Home > Mobile >  I cant use local variable outisde of function
I cant use local variable outisde of function

Time:06-23

I am trying to import function from one code to another, first program is executing .txt file and searching if word exists:

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

Other code:

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!")

Even if word is in databse program prints "This word doesn't exist in database!". Problem is that I can't update local variable exists in function search. I tried to use global exists, it doesn't work! Please help!

CodePudding user response:

You can make the search function return the value.

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!")

CodePudding user response:

It's because you're defining exists again in function scope.

Try 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
    return exists

And,

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!")

CodePudding user response:

Right now your function just sets the variable exists to either 1 or 0. exists is a local variable. By definition you should not have access to it from elsewhere. If you want to know the value you will need to add 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

After adding return, you need to recieve the value somewhere. You can do as suggested in other comments and save it to a variable exists or you can do as I suggest below. Since you will use the result as an if-else to check if the return is 0 or 1 you can immediately check if (search(word)): to get a bit cleaner code.

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()
  • Related