I'm working on a problem that I got from a friend, in this problem I need to generate the time in the following format: 00:00:00, 00:00:01, 00:00:02 etc... But to follow the instructions of this problem correctly I need to use generator functions to accomplish that result. So first of all I need to create three generator functions that generate numbers between 0-59 for secs and mins and 0-23 for hrs. so I tried to do it, and I think that I did everything correctly but I encountered a problem, let's say that we're talking about the gen_func that generates hours for now (I will call it gen_hr), when I try to use the yield command it works, but it only prints to the screen the number 0 which should be only the beggining of what I really want, I'm trying to update the local variable (it's local to the gen_hr generator function), but it's not updating, everytime I try to print the next produced value it prints 0. HERE'S THE CODE:
def gen_hours():
hr = 0
while hr < 24:
if hr < 10:
yield f"0{hr}"
hr += 1
else:
yield hr
hr += 1
AND HERE'S THE OUTPUT:
for i in range(10):
print(next(gen_hours()))
>>> 00
>>> 00
>>> 00
>>> 00
>>> 00
>>> 00
>>> 00
>>> 00
>>> 00
>>> 00
HERE IS THE OUTPUT THAT I WAS EXPECTING:
>>> 01
>>> 02
>>> 03
>>> 04
>>> 05
>>> 06
>>> 07
>>> 08
>>> 09
>>> 10
It would be wonderful if you help me understand what's wrong with my code.
you should first create a generator and then call next
on it:
gen = gen_hours()
for i in range(10):
print(next(gen))
a different way to achieve just that using islice
is:
from itertools import islice
for h in islice(gen_hours(), 10):
print(h)
you code creates a fresh generator in each iteration of the loop and calls next
to always get the first element.