首页 > 解决方案 > 当python中有一个循环时,我怎样才能让我的代码做其他事情

问题描述

我目前正在制作一个不和谐的机器人,我需要它在一些地方制作一些循环,但我还需要它准备好在循环中响应其他人。这是一个简化的示例:

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

在这里,我希望在循环发生时打印你好,而不是在它完成之后

标签: pythonloopsdiscorddiscord.py

解决方案


您需要使用 Asyncio https://docs.python.org/3/library/asyncio.html

这是一个将在“相同”时间打印奇数和偶数的示例。

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())

随意尝试一下,看看它是如何工作的。


推荐阅读