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': ")
关键修改说明
- 补上
import random:原代码缺少这个导入,运行时会直接报错,必须添加 - 替换初始输入为print语句:把
input("Please type 'yes' or 'no': ")改成print("Please type 'yes' or 'no': "),避免第一次不必要的输入 - 优化输入处理:用
strip().lower()处理用户输入,支持大小写(比如Yes、YES)和前后空格,提升程序健壮性 - 增加"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
相关产品推荐
相关产品推荐

