简体   繁体   中英

discord.py Variable doesn't exist out of if statement [python]

I'm trying to build a bot, who answers after its name is written.

@client.event
async def on_message(message):
    trigger =  False

    if message.content.startswith("BOT_NAME"):
        trigger =  True   
        await message.channel.send("Hi")
        #print(trigger) -> False

    if trigger:
        if message.content.startswith("What's up"):
            await message.channel.send("Same Dude")                   
            trigger = False

Normally RETURN causes error in if-statements. It have to be used in function.

But in this case it's working same as break:

if message.author == client.user:
    return

Why it's working like that? I really appreciate all help.

Actually, return is in a function. Anything that is indented under something is under the scope of it, whether that is a function, if statement, class, loop, etc.

Return works exactly like break , but it also returns a value. So lets say you have a function and you want it to "give back" a value. Simply put the value in a variable, then add return behind it, like this:

def addition(lnum, rnum):
    lnum + rnum = sum
    return sum

When called, let's say like result = addition(1, 1) , the function will return the sum of 1 + 1, and it will be assigned to the variable result .

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