Python报UnboundLocalError:变量sports_talk引用前未赋值如何解决?
报错原因
这个UnboundLocalError报错的核心原因是Python的变量作用域规则:
- 如果你在函数内部对一个变量做赋值操作,Python默认会将这个变量识别为局部变量,不会再去读取外部的全局同名变量
- 你代码里的全局变量
sports_talk,在函数what_question_hobby内部,只有choice == "Playing Sports"条件成立时才会被赋值,如果随机选中的爱好不是运动,第二个if sports_talk == True判断时就会读取未赋值的局部变量,直接触发报错。 - 额外注意:原代码还缺少
random模块导入语句,修复完作用域问题后还会触发NameError,需要补上导入语句。
修复方案
方案1:声明使用全局变量(快速修复)
在函数开头加上global sports_talk声明,告诉Python这个变量用的是外部全局作用域的变量,修复后的完整代码如下:
import random 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): global sports_talk # 新增这行声明使用全局变量 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)
方案2:避免使用全局变量(更规范的写法)
全局变量容易引发不可预期的作用域问题,更推荐把状态作为参数传入函数,再把修改后的状态返回,修改示例:
import random 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, sports_talk): 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 return sports_talk if __name__ == "__main__": sports_talk = False while True: talking_input = input("You: ") if talking_input == "What do you enjoy?": sports_talk = what_question_hobby(talking_input, sports_talk)
内容的提问来源于stack exchange,提问作者Terrible Game Developer
相关产品推荐
相关产品推荐

