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

如何修改Python代码实现最多3次非整数输入错误尝试后终止?

限制输入错误尝试次数为3次的代码修正

原需求

现有一段Python代码,功能是获取用户输入的年龄并判断是否成年。需求修改为:输入非整数的错误尝试最多允许3次,3次错误后提示Invalid valid. Try again.并终止程序。

原代码如下:

while True:
    try:
        age = int(input('Age: '))
    except ValueError:
        print("Invalid valid. Try again.")
        continue

    if age >= 18:
        print("You are a grown up!")
    else:
        print("You are a child!")

    break

用户代码问题

用户自行编写的代码仅允许1次错误尝试就终止程序,代码如下:

while True:
    try:
        age = int(input('Age: '))
    except ValueError:
        print("Invalid valid. Try again.")
        print( "Out of tries! ")
        break

    if age >= 18:
        print("You are a grown up!")
    else:
        print("You are a child!")

    break

问题核心:第一次捕获ValueError时直接执行break终止循环,没有对错误次数进行计数和判断,因此只能尝试一次。

正确实现代码

通过添加错误计数器跟踪尝试次数,达到3次后再终止程序:

max_tries = 3
tries = 0

while tries < max_tries:
    try:
        age = int(input('Age: '))
        # 输入有效,判断年龄
        if age >= 18:
            print("You are a grown up!")
        else:
            print("You are a child!")
        break  # 获取有效输入后退出循环
    except ValueError:
        tries += 1
        if tries == max_tries:
            print("Invalid valid. Try again.")
            print("Out of tries!")
        else:
            print(f"Invalid valid. Try again. ({max_tries - tries} tries left)")

代码说明

  • 用max_tries设定最大错误尝试次数,tries记录当前错误次数
  • 循环条件为tries < max_tries,错误次数未达上限时持续尝试
  • 每次捕获ValueError时,错误次数加1,根据次数判断是提示剩余机会还是终止程序
  • 一旦输入有效整数,立即判断年龄并退出循环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:57:17