简体   繁体   中英

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. 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). 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. (I'M STILL USING DISCORD PY 1.7.3 BECAUSE I HAVE NOT CHANGED THE CODE YET TO 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. 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. Also there is a option to use break like this:

while True:
    do_some_stuff()
    break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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