Python 3数学游戏变量未更新问题求助
问题排查与修复方案
核心问题:变量作用域错误
你在difficultysystem函数内给num1、num2赋值时,Python会将它们视为函数局部变量,不会修改game函数或全局作用域的同名变量,导致外部始终使用初始值。
其他待修复的问题
- 整数与字符串直接拼接会报错,需先将整数转为字符串
- 用户输入的答案是字符串类型,需转为整数才能和计算结果比较
points + 1仅做运算未赋值,无法实现加分效果- 递归调用难度选择函数时,未处理返回值,可能导致变量未正确初始化
- 全局变量
num1、num2属于冗余定义,应放在函数内部管理
修复后的完整代码
import random Positive = ["Yes", "yes", "y", "Y"] points = 0 def game(): print("Cool, let's start:") print("Please enter your name: ") name = input() print(" ") print(f"Nice to meet you {name}") print("This game is about math questions. You will get a random question and then will need to proceed to the next one for a total of 5 times. Are you ready?") Begin = input() print(" ") if Begin in Positive: def difficultysystem(): print("Please select your difficulty: hard, medium, or easy.") print("*Note* Please keep in mind you should not use any caps") Difficulty = input() if Difficulty == "easy": return random.randint(1,10), random.randint(1,10) elif Difficulty == "medium": return random.randint(10,50), random.randint(10,50) elif Difficulty == "hard": return random.randint(50,100), random.randint(50,100) else: print(f"Hey {name} seems like we could not find your difficulty, please make sure you wrote it down correctly") print(" ") # 递归调用后返回正确的数值 return difficultysystem() # 通过返回值获取难度对应的num1和num2 num1, num2 = difficultysystem() print("Nice, time to start:") print(f"How much is {num1} * {num2}?") # 将输入转为整数 Answer1 = int(input()) print(" ") if num1 * num2 == Answer1: print("Good job!") global points points += 1 else: print(f"Not quite, the correct answer was {num1 * num2}") else: print("Oki doke, bye") # First start input Start = input("Are you ready to play? ") if Start in Positive: game()
关键修改说明
- 作用域修复:让
difficultysystem函数返回生成的num1和num2,在game函数中接收返回值,彻底解决作用域问题 - 字符串拼接优化:使用f-string简化字符串拼接,同时自动处理整数转字符串
- 输入类型转换:将用户输入的答案转为整数
int(input()),才能和计算结果正确比较 - 加分逻辑修复:用
points += 1替代points + 1,实现分数累加;如果要全局保留分数,需用global声明 - 递归逻辑优化:递归调用
difficultysystem时返回结果,确保最终能拿到有效的数值 - 冗余代码清理:删除不必要的全局变量
num1、num2,以及未使用的matplotlib导入、StartupGame等变量
内容的提问来源于stack exchange,提问作者LPandJL
相关产品推荐
相关产品推荐

