def make_word():    word = ""    for ch  in "spam":        word +=ch        yield word print(list(make_word())) Output: s, sp, spa, spam | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

def make_word():    word = ""    for ch  in "spam":        word +=ch        yield word print(list(make_word())) Output: s, sp, spa, spam

please explain me everything about this code. I can't really understand. thanks

10th Aug 2016, 1:06 PM
Massimo Palladini
Massimo Palladini - avatar
10 Answers
+ 13
#start define function make_word def make_word(): #init variable word to hold an empty string    word = "" #do for loop, in each iterate take next character of the word "spam", first iterate ch=s, second ch=p, third ch=a, and last ch=m    for ch  in "spam": #add ch to string word. so in first iterate word=s, then word=sp, word=spa, word = spam        word +=ch #in each iterate return the current word string # that is the generator uniqe part        yield word ################### end of function #### # now we call to the function that is genarator, and all his return put in list and print the list print(list(make_word())) Output: s, sp, spa, spam
10th Aug 2016, 1:41 PM
‫Ido Tal
‫Ido Tal - avatar
+ 2
thank you so much
10th Aug 2016, 1:49 PM
Massimo Palladini
Massimo Palladini - avatar
+ 2
if I understand correctly, ch is just a variable used on the fly basically, defined by its context in the For statement
15th Feb 2017, 5:04 AM
Joshua Blalock
Joshua Blalock - avatar
+ 1
ch (chain) in 'spam'
10th Aug 2023, 1:24 PM
крол зимний
крол зимний - avatar
0
the 'ch' must be defined in somewhere?
15th Nov 2017, 9:40 AM
jqC
jqC - avatar
0
What is the result of this code? def make_word(): word = "" for ch in "spam": word +=ch yield word What is the result of this code? def make_word(): word = "" for ch in "spam": word +=ch yield word print(list(make_word())) out put ['s', 'sp', 'spa', 'spam'] print(list(make_word()))
28th Apr 2020, 3:36 AM
makhan Kumbhkar
makhan Kumbhkar - avatar
0
out put ['s', 'sp', 'spa', 'spam']
25th May 2021, 5:39 PM
Hayder Jawad Al-ATBEE
Hayder Jawad Al-ATBEE - avatar
0
# now we call to the function that is genarator, and all his return put in list and print the list print(list(make_word())) Output: s, sp, spa, spam
21st Jul 2022, 1:54 AM
duke writer
duke writer - avatar
0
Thank you for your thorough explanation. Could someone explain the ch variable please? I think I understand ch now - it is like i representing a character within the word = "" string. Hence it just selects one character from the word string at a time.
7th Apr 2023, 7:07 AM
Catherine Gomedja
0
def make_word(): word = "" for ch in "spam": word +=ch yield word print(list(make_word())) out: ['s', 'sp', 'spa', 'spam']
13th Nov 2023, 11:10 AM
Mojtaba Ghasemnezhad Moghaddam Ilkhchi
Mojtaba Ghasemnezhad Moghaddam Ilkhchi - avatar