Search code examples
pythonfunctiongeneratoryield

TypeError: 'str' object is not callable in generator python


def gen_secs():
    x = 0
    while x < 60:
        yield x
        x += 1

def gen_minutes():
    x = 0
    while x < 60:
        yield x
        x += 1

def gen_hours():
    x = 0
    while x < 24:
        yield x
        x += 1

def gen_time():
    for x in gen_hours():
        for y in gen_minutes():
            for z in gen_secs():
                yield ("%d:%d:%d" (x, y, z))

for gt in gen_time():
    print(gt)
    if gt == "01:23:45":
        break

the the function gen_time cannot return the string param for some reason. there's syntax problem and I cannot find the issue.


Solution

  • You forget the format str syntax, try change the follow:

    yield ("%d:%d:%d" (x, y, z))
    

    to:

    yield ("%d:%d:%d" % (x, y, z))
    

    This article can be very helpful