【问题标题】:Im not sure how I can fix this but I keep getting the Error UnboundLocalError: local variable 'sports_talk' referenced before assignment on line 56 [duplicate]我不确定如何解决这个问题,但我不断收到错误 UnboundLocalError: local variable 'sports_talk' referenced before assignment on line 56 [重复]
【发布时间】:2021-12-17 09:35:39
【问题描述】:
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)

我不断收到此错误,但我不确定如何修复它UnboundLocalError: local variable 'sports_talk' referenced before assignment on line 56

【问题讨论】:

  • 能否请您发布所有相关代码?此代码不包含调用 what_question_hobby() 的位置或问题和爱好变量是什么。此代码本身不会导致错误。
  • 尝试明确标题,将其余文本添加到正文(不是标题),指定您在哪一行出现错误Wich line is line 56?我>。也不清楚你在哪里调用这个函数。
  • @TadhgMcDonald-Jensen 没关系,非常感谢!

标签: python


【解决方案1】:

当你这样做时

sports_talk = True

在函数内部(在本例中为what_question_hobby),您将在该函数中创建一个新的局部变量,从而隐藏全局sports_talk 变量。如果要修改函数内部的全局变量,必须在函数顶部使用global

def what_question_hobby(questions):
    global sports_talk
    ...

经验法则:避免使用(最重要的是修改)全局变量。为此使用函数参数和返回值。一个简单的例子是:

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

【讨论】:

    猜你喜欢
    • 2023-02-13
    • 1970-01-01
    • 2021-05-11
    • 2017-08-08
    • 2013-02-11
    • 2018-01-22
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多