输入无限循环并引发值错误 - python

Infinite loop with input and raise Value Error- python

我正在使用 python 请求用户输入两个值之间的浮点数。如果它们不在指定值之间,我使用“raise ValueError”。不幸的是,即使组件看起来应该如此,这种配置似乎也不会循环。下面是代码。

while True:                    
    percent_var = float(input("Type in a number between 0 and 100"))
    if percent_var > 100 or percent_var < 0:
        raise ValueError(f"{percent_var} is not between 0 and 100")
        percent_var = float(input("Type in a number between 0 and 100"))
    else: 
        break

如何让死循环继续请求输入,并在输入不符合要求时给出错误信息?

当您 raise 时,它会立即停止执行流程,除非它被捕获。简单的方法是让循环继续,直到你得到你想要的答案:

while True:                    
    percent_var = float(input("Type in a number between 0 and 100"))
    if percent_var > 100 or percent_var < 0:
        print(f"{percent_var} is not between 0 and 100")
    else: 
        break

您可以使用 ValueError,只要将其包装在 try/except 中,以确保在出现错误时它会执行您想要的操作,而不是终止整个函数。

以这种方式使用异常的好处是,它允许您捕获用户输入无效内容的情况 float,并使用执行在这两种情况下完全相同(即打印错误然后继续循环):

while True:  
    try:                  
        percent_var = float(input("Type in a number between 0 and 100"))
        if percent_var > 100 or percent_var < 0:
            raise ValueError(f"{percent_var} is not between 0 and 100")
        break     # the loop only breaks if no exceptions were raised!
    except ValueError as e:
        print(e)  # the loop will automatically continue and try again

或者更简单一点:

while True:  
    try:                  
        percent_var = float(input("Type in a number between 0 and 100"))
        if 0 <= percent_var <= 100:
            break
        raise ValueError(f"{percent_var} is not between 0 and 100")
    except ValueError as e:
        print(e)

用 print 语句替换 raise 关键字,否则它会在预期之前中断。