pythonnltknltk-book

How do I write this into a function in Python 3?


How would I write this into a function that gives the same output?

from nltk.book import text2

sorted([word.lower() for word in text2 if len(word)>4 and len(word)<12])

Solution

  • Functions are defined using the special keyword def followed by a function-name and parameters in parenthesis. The body of the function must be indented. Output is in general passed using the return-keyword. For this particular line of code, you can wrap it as such:

    from nltk.book import text2
    
    def funcName():
       return sorted([word.lower() for word in text2 if len(word)>4 and len(word)<12])
    

    Where funcName can be replaced with any other word, preferably something that describes what the function does more precisely.

    To use the function you would add a linefuncName(). The function will then be executed, after execution, the program returns to the line where funcName was called and replaces it with the return-value of the function.

    You can find more information about functions in the documentation.