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])
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])
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()
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.
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.