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

random.randint生成错误数值:D&D骰子程序仅输出1-4问题

问题原因与修复方案

嘿,这个问题一眼就能揪出根源——你的条件判断写法出了问题!

错误到底在哪?

看你写的条件语句,比如这一行:

if choice == "d4" or "4":

Python里的逻辑运算符or要求两边都是完整的判断表达式。你现在写的or "4",等价于直接判断"4"这个字符串是否为真——而所有非空字符串在Python里都会被判定为True。

这就导致不管用户输入的choice是什么(哪怕是d100),第一个条件都会被判定为True,程序直接执行d4(),自然只会输出1-4的数值了!后面的elif条件根本没机会被触发。

修复方法

你需要把每个条件补全,或者用更简洁的in操作符来检查选项是否在指定集合里:

写法一:补全逻辑判断

if choice == "d4" or choice == "4":
    d4()
elif choice == "d6" or choice == "6":
    d6()
# 其他骰子的判断以此类推

写法二:更简洁的in操作符推荐

这种写法更易读,也不容易犯类似的错误:

choice = input("What dice will you roll: ")
if choice in ("d4", "4"):
    d4()
elif choice in ("d6", "6"):
    d6()
elif choice in ("d8", "8"):
    d8()
elif choice in ("d10", "10"):
    d10()
elif choice in ("d12", "12"):
    d12()
elif choice in ("d20", "20"):
    d20()
elif choice in ("d100", "100"):
    d100()
else:
    print(random.randint(1,20))

额外优化小建议

其实你还能简化重复的函数逻辑,写一个通用的骰子函数,避免大量重复代码:

import random

def roll_dice(sides):
    return random.randint(1, sides)

choice = input("What dice will you roll: ").lower()  # 转小写兼容大小写输入
dice_map = {
    "d4": 4, "4":4,
    "d6":6, "6":6,
    "d8":8, "8":8,
    "d10":10, "10":10,
    "d12":12, "12":12,
    "d20":20, "20":20,
    "d100":100, "100":100
}

if choice in dice_map:
    print(roll_dice(dice_map[choice]))
else:
    print(roll_dice(20))

这样代码更整洁,以后要加新骰子,只需要在dice_map里加一对键值对就行啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:28:51