如何优化Python数学闪卡游戏中大量的条件判断代码?
优化冗余条件判断的方案
针对你当前的代码,最简洁且易维护的优化方式是使用字典映射,把「classical」难度下不同运算符对应的配置数据统一存储,替代重复的if判断逻辑。
具体实现步骤:
- 先定义一个字典,把每个运算符对应的解释文本、数值范围等配置存进去:
classical_operator_configs = { '*': { 'explanation': "Times tables up to the 15's! A classical challenge!", 'difficulty_int1': 1, 'difficulty_int2': 15 }, '/': { 'explanation': "Divide numbers up to 50's! A classical challenge!", 'difficulty_int1': 1, 'difficulty_int2': 50 }, '-': { 'explanation': "Subtract up to the 70's! A classical challenge!", 'difficulty_int1': 1, 'difficulty_int2': 79 }, '+': { 'explanation': "Addition up to the 70's! A classical challenge!", 'difficulty_int1': 1, 'difficulty_int2': 79 } }
- 然后用单一的条件判断处理「classical」难度的逻辑,从字典中取出对应配置赋值:
if optionsScreen.flashcarddifficulty == "classical": optionsScreen.explanationtitle = "Classical -" # 获取当前选中的运算符 current_operator = optionsScreen.flashcardtype # 从字典中匹配配置,get方法可以避免运算符不存在时抛出KeyError operator_config = classical_operator_configs.get(current_operator) if operator_config: optionsScreen.explanation = operator_config['explanation'] optionsScreen.flashcarddifficultyint1 = operator_config['difficulty_int1'] optionsScreen.flashcarddifficultyint2 = operator_config['difficulty_int2'] else: # 可选:处理未知运算符的情况,比如设置默认提示 optionsScreen.explanation = "Unknown operator for classical difficulty!"
这种方式的优势:
- 消除了重复的条件判断,代码结构更清晰
- 后续新增运算符或修改配置时,只需修改字典内容,无需改动逻辑代码,维护成本更低
- 可以通过
get方法轻松处理非法运算符的边界情况,避免程序崩溃
内容的提问来源于stack exchange,提问作者ezratweaver
相关产品推荐
相关产品推荐

