简体   繁体   中英

`for` loop in discord.py does not execute if…elif statements sequentially

As the title states, I created a simple bot using discord.py that responds to a list of commands as such (the code has been truncated for brevity):

import discord
from discord.ext import commands
bot = commands.Bot(command_prefix = '!')

@bot.command()
async def respond_to_me(ctx):

    my_list = [1, 2, 3, 4]

    for item in my_list:
        if item == 1: await ctx.send("You said one")
        elif item == 2: await ctx.send("You said two")
        elif item == 3: await ctx.send("You said three")
        elif item == 4: await ctx.send("You said four")
        else: pass

bot.run(bot_token)

However, executing code with my_list = [1, 2, 3, 4] sometimes returns the following response (which changes randomly with repeated execution):

"You said one"
"You said three"
"You said two"
"You said four"

What is happening? I don't understand how simple code can return different results with each execution? What do I do to prevent this from happening?

A rough solution could be to asyncio.sleep() (will need to import asyncio ) for a little bit after each iteration, so each request has time to be processed in the correct order.

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