简体   繁体   English

如何使用 function 中断 while 循环

[英]How to interrupt a while loop with a function

ok so this is probably so easy but i am trying to find a away for the past 4 hours and i can't find it.好的,所以这可能很容易,但我试图在过去 4 小时内找到一个离开的地方,但我找不到它。 So i have this discord bot where is like a stopwatch, you enter a command and the stopwatch start (i'm using a while loop that each time sleep for 1 second because i find it easier).所以我有这个 discord 机器人,它就像一个秒表,你输入一个命令然后秒表开始(我使用一个 while 循环,每次睡眠 1 秒,因为我发现它更容易)。 Then with another command the stopwatch should stop, but since the while loop started it can't exit to find the boolean that stop it.然后使用另一个命令,秒表应该停止,但由于 while 循环开始,它无法退出以找到停止它的 boolean。 (I'M STILL USING DISCORD PY 1.7.3 BECAUSE I HAVE NOT CHANGED THE CODE YET TO 2.0!!!) (我仍在使用 DISCORD PY 1.7.3 因为我还没有将代码更改为 2.0 !!!)

Here is the code这是代码

from discord.ext import commands
from time import sleep
intents = discord.Intents.default()
intents.members = True

client = commands.Bot(command_prefix='!', intents=intents)

isCounting = False

@client.event
async def on_ready():
    print("The bot logged on")
    print("-----------------")





@client.command()
async def start(ctx, arg):
    await ctx.send("Stopwatch Started")
    isCounting = True
    seconds = 0
    while isCounting == True:
        seconds = seconds + 1
        sleep(1)
        print(seconds)

@client.command()
async def stop(ctx, arg):
        turnoAttivo = False
        await ctx.send("The stopwatch Stopped")

I don't get any errors because the while loop is running, so i don't know how should i do this.我没有收到任何错误,因为 while 循环正在运行,所以我不知道该怎么做。 Thank you.谢谢你。

If you want to stop the loop with a condition, you can use this construction:如果要使用条件停止循环,可以使用以下构造:

is_counting = True

while is_counting:
    do_some_stuff()
    if condition:
        is_counting = False

Thus you set the flag to False by the condition and it interrupts the loop.因此,您根据条件将标志设置为 False,它会中断循环。 Also there is a option to use break like this:还有一个选项可以像这样使用break

while True:
    do_some_stuff()
    break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM