+ 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
10 ответов
+ 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
+ 2
thank you so much
+ 2
if I understand correctly, ch is just a variable used on the fly basically, defined by its context in the For statement
+ 1
ch (chain) in 'spam'
0
the 'ch' must be defined in somewhere?
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()))
0
out put ['s', 'sp', 'spa', 'spam']
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
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.
0
def make_word():
word = ""
for ch in "spam":
word +=ch
yield word
print(list(make_word()))
out:
['s', 'sp', 'spa', 'spam']