如何让某个函数在满足某个条件时停止执行

How to make a certain function stop executing when a certain condition is met

我正在设计一个 discord 机器人,它会在满足特定条件时循环播放特定文本,然后触发此功能 运行。

async def inform(self,message):
    while flag==1:
        await message.channel.send("text")
        await asyncio.sleep(5) 
        await message.channel.send("text2")
        await asyncio.sleep(5) 
        await message.channel.send("text3")
        await asyncio.sleep(5) 
         

现在的问题是,当不再满足条件时,函数会在牵引前完成整个循环。我希望它在条件不再满足时停止。

我想添加一个

if flag==0:
 return

在每一行之后,但这不是我正在寻找的优雅解决方案。

我不希望整个代码都停止 运行ning,而只是这个函数。

我是 python 的初学者,欢迎任何见解:) 谢谢!

循环的每次迭代应该只发送一条消息,为了跟踪消息发送的顺序,我使用了变量 i,它在每次发送消息时递增。

async def inform(self,message):
    i = 0
    while flag==1:
        if i == 0:
            await message.channel.send("text")
            await asyncio.sleep(5) 
        elif i == 1:
            await message.channel.send("text2")
            await asyncio.sleep(5)
        elif i == 2:
            await message.channel.send("text3")
            await asyncio.sleep(5)
        i = (i + 1) % 3

如果我没猜错,你想检查是否满足条件。这是一个无限循环,直到满足某些条件。如果这不是您想要的,请再次说明。

import random
msgs = ['msg1','msg2','msg3']
condition_met = False
while True:
    if condition_met:
        break
        # also return works here
    else:
        await message.channel.send(random.choise(msgs))
        await asyncio.sleep(5)
        if something == 'Condition met here':
            condition_met = True

A​​ while loop,在每次迭代之前都会查看条件是否为True,如果是,它将继续,否则将停止。

while flag == 1:
    if 'some condition met':
        flag = 0
        # And the loop will stop

循环会自动停止,仅此而已。另外最好使用布尔值。

您的代码略有改进

# Defining variables
flag = True
iteration = 0

while flag:
    # Adding `1` each iteration
    iteration += 1
    # Sending the message
    await message.channel.send(f'text{iteration}')
    # Sleeping
    await asyncio.sleep(5)