You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python骰子游戏问题:randint匹配异常及输入范围校验需求

问题排查与解决方法

核心问题:类型不匹配导致判断失效

你代码里的guess_1是input()获取的字符串,而dice是randint生成的整数,字符串和整数用==比较永远不相等,所以哪怕数字猜对了也会显示失败。

解决办法:把输入的字符串转换成整数,用int()函数处理:

guess_1 = int(input("Guess the number on the dice: "))

新增输入范围验证功能

要实现输入超出1-6范围时的错误提示,需要在转换类型后添加判断逻辑,如果输入不在1-6之间,直接提示错误。

完整修正代码

from random import randint

# 获取输入并处理非数字情况
try:
    guess_1 = int(input("Guess the number on the dice: "))
except ValueError:
    print("请输入有效的数字!")
else:
    # 判断输入是否在合法范围
    if not 1 <= guess_1 <= 6:
        print("输入无效,请输入1-6之间的数字!")
    else:
        print(f"You have entered {guess_1}")
        dice = randint(1,6)
        if guess_1 == dice:
            print(f"The result was {dice}. Congratulations, you win!")
        else:
            print(f"The result was {dice}. Sorry, try again!")

代码说明

  • 用try-except捕获输入非数字的情况,避免程序崩溃
  • 新增范围判断,当输入不在1-6区间时直接提示错误
  • 先完成输入验证,再生成骰子数,避免无效输入下做无用操作

内容的提问来源于stack exchange,提问作者Maya_NG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 19:01:00