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

63 Views Asked by At

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])
3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On

I am not sure I understand you correct.

from nltk.book import text2

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

my_func()
0
On

Welcome to StackOverflow! Unfortunately, it is not our jobs to write code FOR you, but rather help you understand where you are running into some errors.

What you want to do is learn how to lowercase strings, write conditionals (like length > 4 && < 12), and sort arrays.

Those are somewhat basic, and easy to learn functionality of python and looking up those docs can get you your answer. Once you are writing your own python code, we can better help you get your solution and point out any flaws.