如何在不停止代码的情况下继续要求 python 中的有效输入

How to keep asking for a valid input in python without stopping the code

您好,我正在尝试让我的代码请求输入,直到输入正确的值。如果输入正确,则它会继续执行其他任务。否则将再次提示用户。我尝试使用 Try/Except 但无法正确使用。我有这个:

while True:
try:
    radius = float(input("Enter radius: "))
    if radius > 1 and radius < 0:
        
        break
        print("Radius must be between 0 and 1. Try again: \n")

except Exception as e:
    print(e)
finally:
    print( 'ok lets go on')
    ### more tasks are performed and stuff ###

为了继续,用户必须输入一个介于 0 和 1 之间的浮动半径。否则它会一直询问。我还是新人,所以感谢您的耐心等待!

有些地方不对。一个数字不可能既是 <0 又是 >1,无论 try 和 [=15= 的结果如何,finally 总是 运行 ] 块,你没有打破 while 循环,所以最终 运行ning 永远。

像这样就可以了:

while True:
    try:
        radius = float(input("Enter radius: "))
        if radius > 1 or radius < 0:
            print("Radius must be between 0 and 1. Try again: \n")
        else:
            break
    except Exception as e:
        print(e)

print( 'ok lets go on')
while True:
    radius = float(input("Enter radius: "))
    if radius > 1 or radius < 0:
        print("Radius must be between 0 and 1. Try again: \n")
        continue
    else:
        print('ok lets go on')

它照你说的做。但是当你想破解代码时,请在评论中告诉我。

your iterations and if conditions are wrong. between 0 to 1 mean we cant get 0 as input we must reject it. and we must reject invalid inputs like strings

radius = float()
    while True:
        try:
            radius = float(input("Enter radius: "))
            if ((radius >= 1) or (radius <= 0)):
                print("Radius must be between 0 and 1. Try again: \n")
                continue
            else:
                break
        except Exception as ex:
            print("Float required !")
            print(ex)
            
    
    print("radius" +  str(radius))
while True:
    try:
        radius = float(input("Enter radius: "))
        if radius < 1.0 and radius > 0.0:
            break
            print("Radius must be between 0 and 1. Try again: \n")

    except Exception as e:
        print(e)
    finally:
        print('ok lets go on')
        ### more tasks are performed and stuff ###

它会很好用 只需更正运算符

之前

  if radius > 1 and radius < 0 :

之后
 if radius < 1.0 and radius > 0.0:

输出

Enter radius: 0.9
ok lets go on

Process finished with exit code 0

代码中有几个问题。

首先,有一个缩进:在循环中重复的代码应该额外缩进(比 while 关键字更深一层。

其次,您检查的条件不正确:应该是 or operator:

if radius > 1 and radius < 0:

(此条件永远不会满足,因为值不能同时小于0和大于1)。

第三,你应该更好地决定何时退出循环。您可以在检查值是否正确后使用 break 关键字明确地执行此操作。在您当前的代码中,如果该值不符合您的[不正确]条件,您将尝试执行此操作。

如果您需要立即开始下一个循环,请使用 continue 关键字。

而且我不明白为什么你需要 finally 块。

所以代码应该看起来不错。像这样:

while True:
    try:
        radius = float(input("Enter radius: "))
        if radius > 1 or radius < 0:
            print("Radius must be between 0 and 1. Try again: \n")
            continue 
            
        break
    except Exception as e:
        print(e)
        continue

print( 'ok lets go on')
### more tasks are performed and stuff ###

最后一个 continue 关键字在这种情况下不是必需的,因为循环会在最后一个语句之后自动重复,但为了代码的可读性,我将它留在那里。