Function code works on IDLE, but the program shuts down

Asked

Viewed 419 times

1

I’m a beginner, I’ve been training in my free time for a couple of months and so far my programs had five lines, very simple. This program taught me several new concepts, and it’s part of a larger program that I intend to do.

def dicionario(palavra):
    f = open("portugues.txt", "r")
    for line in f:
        if palavra in line:
            f.close()
            return "Existe"
    f.close()
    return "Nao existe"

if __name__ == "__main__":
    palavra = input('Digite a palavra a procurar: ')
    dicionario(palavra)
input()

When I use IDLE, I open the file as f, and the for block works, returning "Exists" as long as the word is in the dictionary. When I run the entire program, by Pycharm or Python itself, the program asks for the search word and then paralyzes, with no error message. NOTE: the dictionary (portugues.txt) is in PYTHONPATH, in the same directory as the program. Windows 8 usage. What is missing? I intended to use this function in another program via import, I can do it this way?

  • At the end there’s a input() which is just to wait for you to give a ENTER. Even doing this, the program does not end?

  • The program ends, but the point is that the code does not look for the word. It just stands still. If I type the first line code f = ... until "Exists" is Return, without f.close() it works.

  • I wanted to keep f.close() because of the use of memory. The Portuguese dictionary is from Mozilla.

1 answer

2


Problem solved. It was my mistake. I expected that when I ran the program alone it would give me the answer on the screen. Return only returns a value, but it does not become output on the screen. For this, the code would be:

def dicionario(palavra):
    f = open("portugues.txt", "r")
    for line in f:
        if palavra in line:
            f.close()
            return "Existe"
    f.close()
    return "Nao existe"

if __name__ == "__main__":
    palavra = input('Digite a palavra a procurar: ')
    print(dicionario(palavra))
input()

In this case, with the print() involving the function, it does exactly what I wanted, which was to return on the screen whether the word exists or not, when I rotate the module to test.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.