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

Python骰子游戏输入优化:如何实现用户仅需一次指令输入?

Python骰子游戏输入问题解决

你的代码问题在于重复获取了两次用户输入:第一次是answer = input("Please type 'yes' or 'no': "),第二次是while循环里的answer = input(),所以必须输入两次"yes"才会触发骰子结果。

修改后的代码(完整可用版本)

import random

number = random.randint(1, 6)

print("Do you want to roll the die?")
print("Please type 'yes' or 'no': ")

while True:
    answer = input().strip().lower()
    if answer == "yes":
        print("You have rolled: ", number)
        break
    elif answer == "no":
        print("Maybe next time!")
        break
    else:
        print("Invalid input. Please type 'yes' or 'no': ")

关键修改说明

  1. 补上import random:原代码缺少这个导入,运行时会直接报错,必须添加
  2. 替换初始输入为print语句:把input("Please type 'yes' or 'no': ")改成print("Please type 'yes' or 'no': "),避免第一次不必要的输入
  3. 优化输入处理:用strip().lower()处理用户输入,支持大小写(比如Yes、YES)和前后空格,提升程序健壮性
  4. 增加"no"的响应逻辑:让程序对"no"也有合理反馈,更完整

如果不需要处理"no",可以用简化版:

import random

number = random.randint(1, 6)

print("Do you want to roll the die?")
print("Please type 'yes' or 'no': ")

while True:
    answer = input().strip().lower()
    if answer == "yes":
        print("You have rolled: ", number)
        break
    else:
        print("oh.")

修改后用户只需要输入一次指令,就能触发对应逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 12:35:14