Follow me to learn 🐍 Python in 5-minute a day fun quizzes!
You mastered iterables
, didn't you? Then it's time for generators
and the spell yield
!
Quiz
Which code sample correctly uses the yield
keyword in Python to make a count-down?
Sample 1
def count_down(number):
while number > 0:
yield number
number -= 1
for count in count_down(5):
print(count)
Sample 2
def count_down(number):
for i in range(number):
return i
for count in count_down(5):
print(count)
Post your answer in the comments – is it 0 for the first sample or 1 for the second! As usually, the correct answer will be explained in the comments.
Top comments (0)