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

使用Python random包开发骰子程序时出现空白文本问题求助

Fixing Your Dice Roller Program Issues

Hey there! Let's break down what's causing the blank text and other quirks in your dice program, then fix it up.

First, the main problems in your original code:

  • Random numbers are generated too early: You're creating all dice values (D4-D20) as soon as the program starts, instead of generating them after the user picks a dice type. That means even if the user chooses D4 later, the number was fixed at launch—plus unused dice values are just wasting memory.
  • Incomplete input statement: Your diceI = inpu... line is cut off. Without a full input() call, the program might hang or behave unpredictably, leading to that blank text you're seeing.
  • Unnecessary variable: The age = int(D4) line doesn't serve any purpose here; it's just assigning the D4 value to a variable you never use.

Here's the fixed code with explanations:

from random import randint
import os
import time

os.system('cls')
print("What dice would you like to roll?")
print("D4, D6, D10, D12, D20")

# Get and clean up user input (handles lowercase/extra spaces)
dice_choice = input("Enter your choice: ").strip().upper()

# Generate the random number ONLY when the user selects a dice
if dice_choice == "D4":
    roll_result = randint(1, 4)
    print(f"You rolled a {roll_result}!")
elif dice_choice == "D6":
    roll_result = randint(1, 6)
    print(f"You rolled a {roll_result}!")
elif dice_choice == "D10":
    roll_result = randint(1, 10)
    print(f"You rolled a {roll_result}!")
elif dice_choice == "D12":
    roll_result = randint(1, 12)
    print(f"You rolled a {roll_result}!")
elif dice_choice == "D20":
    roll_result = randint(1, 20)
    print(f"You rolled a {roll_result}!")
else:
    print("Oops, that's not a valid dice option. Try again!")

Key improvements:

  1. Lazy random generation: We only create the random number after the user picks their dice, so each roll is fresh and relevant.
  2. Robust input handling: Using .strip().upper() ensures input like d4 or D4 still works correctly.
  3. Clear feedback: The program tells the user exactly what they rolled, and gives an error message for invalid choices—no more confusing blank spaces.
  4. Clean imports: Instead of importing everything from random, we only import randint—this is better practice for clarity and avoiding namespace clutter.

This should eliminate the blank text issue and make your program work as expected for D4 (and all other dice once you test them!).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:53:21