+ 1

Maybe I don't understand generator o func

I need to split a sentence and create a list of word , and I don't know with def ... I complete task for error " print(list(txt.split())) " can you help me ? txt = input() def words(): print(list(words()))

7th Aug 2020, 1:07 AM
Lime
Lime - avatar
8 Réponses
+ 1
''' You are so close! :) I think something like this is what you want? ''' ### x=input() def words(): print(x.split()) words()
7th Aug 2020, 2:31 AM
Steven M
Steven M - avatar
+ 1
There are some other ways to do this, but remember your indentation, especially for functions. The "def" means you are creating or "defining" a new word in the Python language, so all the lines of code that are indented below the "def" belong to that new word. Then, you have to use the new word, or "call" it. So here, we defined "words()" and it takes an input, splits it, puts it in a list and then prints it. However, if we never called "words()" like we do on the last line, it will not perform any action
7th Aug 2020, 2:38 AM
Steven M
Steven M - avatar
+ 1
Solution T.T maybe I understand this code and how to use method , thanks lot for help me =) =≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠= txt = input() def words(): for words in txt.split(): yield words print(list(words())) =≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠=≠
7th Aug 2020, 2:50 AM
Lime
Lime - avatar
+ 1
Yeah generators are a bit different, they yield results. Generators produce generator objects which require iteration through the use of the "next()" command. The word yield comes from an old program design, where the program would stop using resources, it would yield the processor back to the computer. So generators are very efficient at handling resources. Does something like this help? ### x=input() # hello foo bar world def words(): for each in x.split(): yield each word=words() print(next(word)) # hello print(next(word)) # foo print(next(word)) # bar print(next(word)) # world
7th Aug 2020, 2:54 AM
Steven M
Steven M - avatar
+ 1
You are welcome, take care and happy coding
7th Aug 2020, 3:01 AM
Steven M
Steven M - avatar
0
Also , now o try ,but the exercise ask me to define de func and then print it 🤔
7th Aug 2020, 2:33 AM
Lime
Lime - avatar
0
i think the exercise wants me to use yield, but i don't know how to use it, or maybe i just don't know how to create a function to separate a sentence and create a list
7th Aug 2020, 2:36 AM
Lime
Lime - avatar
0
Like this , now I have a wrong program that take the sentenceand the output give [t h e u ni v e r s etc] but the exercise is " the universe is big , the output is [ 'the', 'universe', 'is', 'big'] ================================== txt = input() def words(): for i in txt: yield i print(list(words())) ================================== This my wrong program
7th Aug 2020, 2:42 AM
Lime
Lime - avatar