1

I am creating a python code that does the following:

1 - creates an asynchronous function called "nums" than prints random numbers from 0 to 10 every 2 seconds. 2 - execute a function that prints "hello world" every 5 seconds. 3 - if the function "nums" prints 1 or 3, break the loop and end the program.

The thing is, it's not breaking out of the loop. What I am supposed to do? Thank you.

import asyncio import random async def nums(): while True: x = print(random.randint(0, 10)) await asyncio.sleep(2) if x == 1 or x == 3: break async def world(): while True: print("hello world") await asyncio.sleep(5) async def main(): while True: await asyncio.wait([nums(), world()]) if __name__ == '__main__': asyncio.run(main()) 
1
  • 1
    Have you done any debug printing? The print function returns nothing, so x will always be None. Commented Oct 17, 2022 at 20:55

1 Answer 1

2

You can use return_when=asyncio.FIRST_COMPLETED parameter in asyncio.wait:

import asyncio import random async def nums(): while True: x = random.randint(0, 10) print(x) if x in {1, 3} break await asyncio.sleep(2) async def world(): while True: print("hello world") await asyncio.sleep(5) async def main(): task1 = asyncio.create_task(nums()) task2 = asyncio.create_task(world()) await asyncio.wait({task1, task2}, return_when=asyncio.FIRST_COMPLETED) if __name__ == "__main__": asyncio.run(main()) 

Prints (for example):

5 hello world 6 6 hello world 1 <program ends here> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.