如何在Python if分支中实现随机判定逻辑?现有def行触发报错
慢移动分支随机判定逻辑修正指南
原代码报错与逻辑缺陷
- 触发行内报错的直接原因:
def dice_roll()末尾缺少Python函数定义要求的冒号: - 自定义骰子函数仅定义未调用,直接使用
DiceRoll变量会触发未定义变量错误 - 缺失掷出2时的存活分支处理,不符合需求的双分支逻辑要求
- 将函数定义嵌套在业务if分支内,属于冗余写法,重复定义函数既增加运行开销,也容易混淆变量作用域
前置依赖要求
需要在代码最顶部提前导入用到的模块:import randomimport time
可运行的实现方案
按需选择以下任意一种写法:
轻量化实现(无冗余函数,适合仅当前分支用到随机判定的场景)
if response11 == 'slowly' or response11 == 'slow': dice_result = random.randint(1, 2) if dice_result == 1: print('Bad luck, you were too slow\n\nand got eaten by the bugs!') time.sleep(4) else: # 此处补充掷出2时的存活后续逻辑,例如放行下一步游戏操作、打印存活提示等 print('You moved slowly enough to avoid the bugs, keep going!')
复用骰子逻辑实现(适合后续其他分支也要用到随机判定的场景)
# 骰子函数定义放在全局作用域,仅需定义一次 def dice_roll(): return random.randint(1, 2) if response11 == 'slowly' or response11 == 'slow': dice_result = dice_roll() if dice_result == 1: print('Bad luck, you were too slow\n\nand got eaten by the bugs!') time.sleep(4) else: # 此处补充掷出2时的存活后续逻辑 print('You moved slowly enough to avoid the bugs, keep going!')
内容的提问来源于stack exchange,提问作者EggBlack
相关产品推荐
相关产品推荐

