If I execute this piece of code I get an empty list:
#quick.py
def test(key):
print('the input key is:',key)
if key==1:
return range(1,13)
else:
month = ['15','30']
for i in range(1,53):
if i==4:
yield '2904'
else:
str_i = str(i)
if i<10:
str_i= '0'+str_i
yield month[0] + str_i if i % 2 else month[1] + str_i
my_list = list(test(1))
print('the list is :' ,my_list)
pc@pc-host:~/Git/PasivicSerious$ python3 quick.py
the input key is: 1
the list is : []
but without the " else " I get my desired list:
def test(key):
print('the input key is:',key)
if key==1:
return range(1,13)
# else:
# month = ['15','30']
# for i in range(1,53):
# if i==4:
# yield '2904'
# else:
# str_i = str(i)
# if i<10:
# str_i= '0'+str_i
# yield month[0] + str_i if i % 2 else month[1] + str_i
my_list = list(test(1))
print('the list is :' ,my_list)
pc@pc-host:~/Git/PasivicSerious$ python3 quick.py
the input key is: 1
the list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Why does this happen, what am I misunderstanding about generators?
Aucun commentaire:
Enregistrer un commentaire