1

I came across the following function:

def load_words():
    """
    Returns a list of valid words. Words are strings of lowercase letters.

    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline() # reads one entire line from a file (as a string)
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist 

wordlist = load_words()

I don't understand the assignment of the function load_words() to the variable wordlist? When the variable is assigned, the function gets executed.

Is wordlist the function load_words()? Or is it the return of the function load_words()?

1
  • wordlist = load_words() is conceptually not different from inFile = open(WORDLIST_FILENAME, 'r') - a function is called and whatever the function returns is assigned to the variable. Commented Apr 8, 2020 at 11:24

1 Answer 1

1

When you give:

wordlist = load_words()

you are running the function load_words() and assigning the return value wordlist to the variable wordlist outside the function.


  • You can also run functions without assigning it to a variable, like:

    load_words() but here the wordlist variable you return, is not stored anywere in the python (i mean the current shell) for further use. The wordlist inside the function is a local variable and is valid only inside the function.

  • So when you give wordlist = load_words(), wordlist now becomes a global variable, so that you you call it when you require it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.