使用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 fullinput()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:
- Lazy random generation: We only create the random number after the user picks their dice, so each roll is fresh and relevant.
- Robust input handling: Using
.strip().upper()ensures input liked4orD4still works correctly. - Clear feedback: The program tells the user exactly what they rolled, and gives an error message for invalid choices—no more confusing blank spaces.
- Clean imports: Instead of importing everything from
random, we only importrandint—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
相关产品推荐
相关产品推荐

