0
sports_talk = False
sports = ["Basketball", "Football", "Soccer"]
sports_response = ["What sports do you play?", "what sports do you play?"]
hobbies = ["Programming", "Playing Sports", "Art", "Singing", "Playing the Piano", "Watching YouTube"]
def what_question_hobby(questions):
   choice = random.choice(hobbies)
   if choice == "Playing Sports":
      sports_talk = True
      print(sports_talk)
      print("Bot: " + choice)
   if sports_talk == True:
      print("/hint ask him what sports he plays")
      info = input("You: ")
      if info in sports_response:
        print("Bot: " + random.choice(sports))
        sports_talk = False
while True:
    talking_input = input("You: ")
    if talking_input == "What do you enjoy?":
        what_question_hobby(talking_input)

I keep getting this error, but I am unsure how to fix it UnboundLocalError: local variable 'sports_talk' referenced before assignment on line 56

  • Could you please post all the relevant code? This code doesn't contain where `what_question_hobby()` is getting called from or what the questions & hobbies variables are. This code on its own does not cause an error. – JacksonB Nov 02 '21 at 22:17
  • try to make a clear title, add the rest of the text to the body (not the title), specify in what line you are having the error *Wich line is line 56?*. It's not clear where you are calling this function either. – Ulises Bussi Nov 02 '21 at 22:17
  • @TadhgMcDonald-Jensen Nevermind thank you so much! – Terrible Game Developer Nov 02 '21 at 22:42

1 Answers1

1

When you do

sports_talk = True

inside a function (in this case, what_question_hobby), you're creating a new, local variable in this function, thus shadowing the global sports_talk variable. If you want to modify a global variable inside a function, you must use global at the top of the function:

def what_question_hobby(questions):
    global sports_talk
    ...

A rule of thumb: avoid using (and most important, modifying) global variables. Use function parameters and return values for that. A simple example would be:

def what_question_hobby(questions, sports_talk): 
    choice = random.choice(hobbies)
    if choice == "Playing Sports":
        result = True
        print(result)
        print("Bot: " + choice)

        # Return the value
        return result

    # Access the parameter
    if sports_talk == True:
        print("/hint ask him what sports he plays")
        info = input("You: ")
        if info in sports_response:
          print("Bot: " + random.choice(sports))
          return False
enzo
  • 9,861
  • 3
  • 15
  • 38