Answer Help - Day 39 - 100DaysOfCode

When I run this, it returns an error that countgb is referenced before assignment, but haven’t I assigned it at the very top of the program?

import random

listOfWords = ["british", "suave", "integrity", "accent", "evil", "genius", "Downton"]
wordChosen = random.choice(listOfWords)
wordlength = len(wordChosen)
badGuess = []
countbg = 0
  
def guessMatch():
  if guess.lower() not in wordChosen:
    badGuess.append(guess.lower())
    countbg += 1
    totalguesses = 6
    print(f"Nope! '{guess}' is not in the word. You have {totalguesses-countbg} remaining.")
  else:
    for i in wordChosen:
      if i == guess:
        print(f"{i} ",end="")
      else: 
        print("_ ", end="")
      print()
      print("Good guess!")

print(f"Try to guess the word which has {wordlength} letters!")
print()
for letter in wordChosen:
  print("_ ",end="")
print()
while True: 
  print()
  guess = input("Guess a letter: ")
  print()
  print(f"Your guess is {guess}")
  print()
  guessMatch()
  print()
  if countbg < 6: 
    continue
  else: 
    print("You lost! Sorry!")
    break
  

You have declared countbg in the global scope, but you are trying to modify it inside the guessMatch function without explicitly declaring it as global inside the function. When you assign a value to a variable inside a function, it is considered a local variable unless you explicitly declare it as global.

So, to fix this you just need to add a global statement for countbg at the beginning of the guessMatch function.