[SOLVED] I've two functions both have for loop each, All I want is too run the function one by one with one iteration only

Issue

MY code:-

def looping():
for i in range(1,4):
    print('*')

def not_looping():
for j in range(1,4):
    print('-')

looping()
not_looping()

Output I got:-

*
*
*
-
-
-

Output I want

*
-
*
-
*
-

I’ve also visited this post, And applied my logic as per the post, But still It’s providing me same output.

Solution

Maybe you want generators?

def a_gen():
    for _ in range(4):
        yield "*"

def b_gen():
    for _ in range(4):
        yield "-"


ag = a_gen()
bg = b_gen()

while (a := next(ag, None)) and (b := next(bg, None)):
    print(a)
    print(b)

Note: This while loop will terminate as soon as one of the two generators has been exhausted. In this case, both generators happen to yield the same number of objects.

Answered By – Paul M.

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published.