程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

我不确定如何解决这个问题,但我不断收到错误 UnboundLocalError: local variable 'sports_talk' referenced before assignment on line 56 [重复]

发布于2022-10-06 22:15     阅读(222)     评论(0)     点赞(1)     收藏(3)


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


解决方案


当你这样做

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


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/1793561/0a62594b997a8617b2ac/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

1 0
收藏该文
已收藏

评论内容:(最多支持255个字符)