Search code examples
pythondiscord.pyglobal-variables

How would I avoid using a global variable here?


I know that using global variable is a bad habit so I am trying to remake my black jack program with out them. Currently this code prints out the player's hand (pH) but does not print the worth of the player hand (pHnum). Sorry I know this is a lot of code the place where the problem is happening is the "await ctx.send(pHnum)" its no sending the value I want it to. I know how I would fix this using a global var but is there any other way??? Code below.


  # lists
  pH = []
  dH = []

  # Hand Values 
  pHnum = 0
  dHnum = 0
  
   
  
  # The starting player hand 
  async def playerHand():
    addCardP(pHnum, pH); 
    addCardP(pHnum, pH);
    await ctx.send(pH)
    await ctx.send(pHnum)

    
  # Adding a card to the player hand 
  def addCardP(pHnum, pH):
    # Creating a Card
    Card = randint(2,14)
    # Creating a Suit
    suit = randint(1,4)
    if (suit == 1):
      suit = '♤'
    elif (suit == 2):
      suit = '♡'
    elif (suit == 3):
      suit = '♢'
    elif (suit == 4):
      suit = '♧'
    # For if the card is less then 10; 2-10
    if (Card <= 10): 
      pHnum = pHnum + Card
      Card = str(Card)
      cardS = Card + suit
      pH.append(cardS)
    # If the card is greater then 10; 11-14
    else: 
      if (Card == 14):
        Card = 'A'
        cardS = Card + suit
        pH.append(cardS)
      else: 
        pHnum =+ 10
        if (Card == 11):
          Card = 'J'
          cardS = Card + suit
          pH.append(cardS)
        elif (Card == 12):
          Card = 'Q'
          cardS = Card + suit
          pH.append(cardS)
        elif (Card == 13):
          Card = 'K'
          cardS = Card + suit
          pH.append(cardS)
    return pH, pHnum

I would like to find out a way to not use global vars. So sorry if this is a dumb question I am new to coding as a whole. Thanks so much for the help in advance. Hope you have a great rest of your day!!


Solution

  • You need to assign the result back to the variables.

    async def playerHand():
        pH = []
        phNum = 0
        pH, pHnum = addCardP(phnum, pH)
        pH, pHnum = addCardP(phnum, pH)
        await ctx.send(pH)
        await ctx.send(pHnum)