如何让 try/Exception 语句继续? [重复]

问题描述 投票:0回答:1

如果它得到的值不可接受,我需要它重新运行初始输入问题。

     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 语句,如何获取代码再次要求用户输入?我对此真的很陌生。

python try-catch continue
1个回答
0
投票

你可以试试这个方法吗? While循环将继续直到大于0

try:
    hours = float(input("Please enter your hours worked: "))
    while 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("error occured")
    
© www.soinside.com 2019 - 2024. All rights reserved.