Home > other >  Discord.Py Assigning values to variables
Discord.Py Assigning values to variables

Time:02-07

@commands.command()
    async def reroll(self, ctx, channel: discord.TextChannel, id_ : int):

      try:
        new_gaw_msg = await ctx.channel.fetch_message(id_)
      except:
        await ctx.send("Failed to parse command. ID was incorrect.")
        return
        
      winners = int(winners.replace("W",""))
      users_mention = []
      for i in range(winners):
        users = await new_gaw_msg.reactions[0].users().flatten()
        users.pop(users.index(self.client.user))
        winner = random.choice(users)
        users_mention.append(winner.mention)
        users.remove(winner)
        
        displayed_winners = ",".join(users_mention)

      await ctx.send(f"Congragulations {displayed_winners}! You have won the **{prize}**.\n{gaw_msg.jump_url}")

variable winners is referenced before assignment. I gave value to winners before using it so idk why it doesnt work. Any help is appreciated :D

CodePudding user response:

You are trying to perform an operation on the winners variable before it was created.

There is a thing called name "namespace". Basically, variables created globally (without indent) and variables created locally (inside functions or loops) are different variables.

If you want to specifically use a global variable inside the function, you should first declare that the variable will be global by writing global variable_name inside the function. And only then you can perform operations with it.

There are some hidden dangers with the usage of global variables, so I suggest you read more about python namespaces and global keyword by yourself.

  •  Tags:  
  • Related