0

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.

Bhavya Lodaya
  • 140
  • 1
  • 10

1 Answers1

0

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.

Paul M.
  • 10,481
  • 2
  • 9
  • 15
  • I got your code it works properly but what if the values are different suppose if range is not same then what will be the output – Bhavya Lodaya Mar 17 '22 at 13:27
  • In that case, the while loop will end as soon as the "shorter" generator is exhausted, and the remaining objects in the other generator will not be yielded/printed. What's your actual use-case? – Paul M. Mar 17 '22 at 15:39
  • Actually I've heard of generators but never used it, So I had ask about mixed range in the comment. But Thank you you're code worked for me. – Bhavya Lodaya Mar 17 '22 at 20:52