首页 > 解决方案 > 如何在不停止代码的情况下继续在 python 中请求有效输入

问题描述

嗨,我试图让我的代码要求输入,直到输入正确的值。如果输入正确,则继续执行其他任务。否则将再次提示用户。我尝试使用 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 之间的浮点半径。否则它会一直询问。我还是新手,所以感谢您的耐心等待!

标签: pythonloopsinputtry-except

解决方案


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


推荐阅读