如何为Python掷骰子代码添加非法输入校验与重试逻辑
掷骰子程序的输入校验优化
现有实现掷骰子功能的Python代码运行正常,但存在一个问题:当用户输入yes/no以外的内容时,无法提示「无效选项,请输入yes或no」并重新发起输入请求,以下是补充该逻辑的实现方案。
原代码
import random def roll_dice(): dice_drawing = { 1:( "_________", "| 1 |", "| * |", "----------" ), 2:( "__________", "| 2 |", "| * * |", "-----------" ), 3:( "__________", "| 3 |", "| * * * |", "-----------" ), 4:( "__________", "| 4 |", "| * * * * |", "-----------" ), 5:( "__________", "| 5 * |", "| * * * * |", "-----------" ), 6:( "__________", "| * 6 * |", "| * * * * |", "-----------" ) } roll = input('Roll the dice Yes/No: ') while roll.lower() == 'yes'.lower(): dice1 = random.randint(1,6) dice2 = random.randint(1,6) print('dice rolled: {} and {}'.format(dice1,dice2)) print("\n".join(dice_drawing[dice1])) print("\n".join(dice_drawing[dice2])) roll = input('Roll the dice Yes/No: ') if roll not in roll: roll = input('Roll the dice Yes/No: ') roll_dice()
优化后的代码
import random def roll_dice(): dice_drawing = { 1:( "_________", "| 1 |", "| * |", "----------" ), 2:( "__________", "| 2 |", "| * * |", "-----------" ), 3:( "__________", "| 3 |", "| * * * |", "-----------" ), 4:( "__________", "| 4 |", "| * * * * |", "-----------" ), 5:( "__________", "| 5 * |", "| * * * * |", "-----------" ), 6:( "__________", "| * 6 * |", "| * * * * |", "-----------" ) } # 专门处理输入校验的函数 def get_valid_input(): while True: user_input = input('Roll the dice Yes/No: ').strip().lower() if user_input in ['yes', 'no']: return user_input print('无效选项,请输入yes或no') roll = get_valid_input() while roll == 'yes': dice1 = random.randint(1,6) dice2 = random.randint(1,6) print('dice rolled: {} and {}'.format(dice1,dice2)) print("\n".join(dice_drawing[dice1])) print("\n".join(dice_drawing[dice2])) roll = get_valid_input() roll_dice()
关键修改说明
- 新增
get_valid_input()函数,封装输入校验逻辑:- 循环获取用户输入,自动去除首尾空格并转为小写
- 仅当输入为
yes或no时返回结果,否则打印错误提示并继续循环
- 替换所有直接调用
input()的地方为get_valid_input(),确保每次输入都经过校验 - 简化原循环条件的判断逻辑,因为校验函数已经返回标准化的小写有效值
内容的提问来源于stack exchange,提问作者ALEXANDER ABRAHAM
相关产品推荐
相关产品推荐

