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

Python列表成员检测方法及猜数字游戏代码问题求助

解决猜数字游戏的输入验证问题

嘿,我明白你遇到的麻烦了——当用户输入不在指定的数字列表里时,代码没法让用户重新输入,对吧?咱们来一步步把这个问题搞定。

首先得说清楚你代码里的核心问题:你的guess()函数里没有循环来处理非法输入,所以当用户输入不符合要求的值时,代码不会重复请求输入,直接就卡壳或者往下走了(毕竟你贴的代码还没写完)。

修复方案:给输入环节加上验证循环

我们需要在获取用户输入的地方加一个while循环,只要输入不在numbers列表里,就一直提示用户重新输入。同时我也帮你完善了整个游戏的流程逻辑,让它能正常循环运行起来。

下面是修正后的完整代码:

import random
import math
import time

repeat = True
numbers = ["1", "2", "3", "4", "5"]

def guess():
    chosen_number = random.choice(numbers)
    print("Guess the number I chose between 1 and 5:")
    
    # 循环获取输入,直到输入合法
    while True:
        guess_number = raw_input("> ")
        if guess_number in numbers:
            break
        print("Invalid input! Please enter a number from 1 to 5.")
    
    # 判断猜测是否正确
    if guess_number == chosen_number:
        print("Congratulations! You guessed it right!")
    else:
        print(f"Oops, wrong answer. The number was {chosen_number}.")

# 游戏主流程
while repeat:
    start_choice = raw_input("Do you want to play the number guessing game? (yes/no): ").lower()
    if start_choice == "yes":
        guess()
        # 询问是否继续游戏,同样加输入验证
        while True:
            continue_choice = raw_input("Do you want to play again? (yes/no): ").lower()
            if continue_choice in ["yes", "no"]:
                break
            print("Please enter 'yes' or 'no'.")
        if continue_choice == "no":
            repeat = False
            print("Thanks for playing!")
    elif start_choice == "no":
        repeat = False
        print("Maybe next time!")
    else:
        print("Invalid input! Please enter 'yes' or 'no'.")

关键修改点说明:

  • 输入验证循环:不管是猜数字的输入,还是游戏开始/继续的选择,都用了while True循环,只有当输入符合要求(在指定列表里)时才跳出循环,确保用户必须输入合法值才能继续。
  • 完善游戏流程:把游戏的启动、单次游戏、续玩询问的逻辑整合在一起,让整个流程更顺畅完整。
  • 友好提示:当用户输入非法值时,给出明确的提示信息,告诉用户应该输入什么,体验更友好。

这样修改后,完全符合你的预期——只要输入不在指定范围内,就会要求用户重新输入,游戏也能正常循环运行啦!

内容的提问来源于stack exchange,提问作者Elvez The Elf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:31:59