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

如何让try/except语句在输入不合法时重新请求用户输入?

如何让程序在输入不合法时重新请求输入?

我希望当获取到不合法的输入值时,程序能重新执行初始的输入提问。现有代码如下:

try:
    hours = float(input("Please enter your hours worked: "))
    if hours < 1 :
        print("Please enter a value greater than 0 ")
        #continue isn't working, figure out how to loop back to top instead
                    #temporary placeholder fix  
        hours= int(input("Please enter your hours worked: "))
#if a non-numerical value is entered
except:
    print("Please enter a numerical value greater than 0")
       #temporary placeholder fix  
            hours= int(input("Please enter your hours worked: "))

我尝试使用continue语句但无效,作为编程新手,想了解如何让代码在输入不通过if判断或触发except时再次请求输入?

解决方案

你的代码缺少循环结构,continue只能在while/for这类循环中生效,所以直接使用不会起作用。我们可以用while True创建一个无限循环,直到输入合法才退出循环。

修改后的代码:

while True:
    try:
        hours = float(input("Please enter your hours worked: "))
        if hours > 0:
            break  # 输入合法,跳出循环
        print("Please enter a value greater than 0 ")
    except ValueError:
        print("Please enter a numerical value greater than 0")

关键说明:

  • while True:让代码持续循环执行,直到遇到break语句才停止。
  • 精准捕获ValueError:避免用空except捕获其他意外错误(比如程序自身的异常),只处理输入非数值的情况。
  • 输入校验通过后执行break:退出循环后,后续可正常使用hours变量;如果不通过,打印提示后自动回到循环开头,重新请求用户输入。

这个写法会持续要求输入,直到用户提供符合要求的数值,比你之前的临时修复更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 19:37:10