0

I am currently making a discord bot, and I need it to make some loops in places but I also need it to be ready to respond to other people while it's in the loop. Here's a simplified example:

n = 40
while n > 0:
  print(n)
  n -= 1
print('Hello')

Here I want the hello to be printed while the loop is happening, not after it finishes

WaterPidez
  • 17
  • 2

2 Answers2

1

You need to use Asyncio https://docs.python.org/3/library/asyncio.html

Here's an example that will print odd and even numbers at the "Same" time.

import asyncio, time

#prints out even numbers
async def func1():
    evenNumbers = [num for num in range(50) if num % 2==0]
    for num in evenNumbers:
        await asyncio.sleep(1)
        print(num)

#prints out odd numbers
async def func2():
    oddNumbers = [num for num in range(50) if num % 2!=0]
    for num in oddNumbers:
        await asyncio.sleep(1)
        print(num)

#handles asynchronous method calling
async def main():
    await asyncio.gather(
        func1(),
        func2()
    )

asyncio.run(main())

Feel free to try it out and see how it works.

Peter Jones
  • 191
  • 5
1

I'm not sure for discord bot, but in general, you can use threading to do multiple things at the same time.

For example :

import threading

def thread_function():
    n = 40
    while n > 0:
        print(n)
        n -= 1

th = threading.Thread(target=thread_function)
th.start()

print('Hello')
patate1684
  • 639
  • 3
  • 17