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

如何循环try-except代码直至解决输入异常及负数错误?

Fixing the Loop for Valid Cat Count Input

Hey there! Let's tweak your code so it keeps prompting the user until they enter a valid non-negative integer. The core idea is using an infinite loop that only exits once we get a valid input. Here's how to make it work:

Modified Code

while True:
    print('How many cats do you have?')
    numCats = input()
    try:
        # Convert input to integer once, reuse it for all checks
        cat_count = int(numCats)
        if cat_count >= 4:
            print('That is a lot of cats.')
            break  # Exit loop since input is valid
        elif cat_count < 0:
            print("You can't have negative cats, dumbo")
            # No break here—loop restarts to ask again
        else:
            print('That is not that many cats')
            break  # Exit loop for valid non-negative input
    except ValueError:
        print('You did not enter a number')
        # No break here—loop restarts to ask again

How This Works

  • while True: This sets up an infinite loop that runs nonstop until we hit a break statement. It’s perfect for forcing the user to keep trying until they provide valid input.
  • Single Integer Conversion: We convert the input string to an integer once inside the try block, instead of repeating the conversion in each condition check. This is cleaner and more efficient.
  • Handling Invalid Cases:
    • If the user enters non-numeric text (like "six"), the ValueError triggers, we print an error message, and the loop starts over without exiting.
    • If the user enters a negative number, we call out the mistake but don’t exit the loop—giving them another shot to enter a valid number.
  • Exiting the Loop: Only when the user enters a valid non-negative integer (0 or higher) do we print the appropriate response and use break to stop the loop.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:22:52