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

Python随机数游戏:如何添加无效输入提示并实现循环输入?

猜数游戏输入验证修复方案

你的代码已经具备基础验证逻辑,但缺少无效输入时的提示反馈,这就是之前尝试没达到预期的原因。下面是修改后的代码,能实现你需要的功能:

from random import randint

def validateNumber(number):
    return 1 <= number <= 10

game_1 = randint(1, 10)
while True:
    is_valid = False
    while not is_valid:
        try:
            number_in = int(input("Guess which number from 1-10 that will come up: "))
            if validateNumber(number_in):
                is_valid = True
            else:
                print("That is not a valid input")
        except ValueError:            
            print("That is not a valid input")
    if number_in == game_1:
        print(f"The result was {game_1}. Congrats!")
        break
    else:
        print(f"The result was {game_1}. Try again")
        game_1 = randint(1, 10)

修改说明:

  • 将原来直接赋值is_valid = validateNumber(number_in)改为if-else判断,当数字不在1-10范围内时,会打印指定提示,同时保持循环等待有效输入
  • 在except ValueError块中添加提示语句,用户输入非整数内容(比如字母、符号)时,也会触发无效输入提示
  • 两种无效场景(范围错误、非数字输入)都能覆盖,且会持续循环直到用户输入符合要求的数字

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:02:24