如何运行一个while循环只要不报错

How to run a while loop as long as there is no error

我正在 运行 宁一个可能会出错的代码,但我想 运行 它只要 没有错误。

我想过类似的事情:

while ValueError:
    try:
        x = int(input("Write a number: "))
    except ValueError:
        x = int(input("You must write a number: "))`

你离得很近

while True:
    try:
        x = int(input("Write a number: "))
        break
    except ValueError:
        print("You must write a number: ")

要了解有关异常处理的更多信息,请参阅 documentation

作为 Bhargav 回答的补充,我想我会提到另一个选项:

while True:
    try:
        x = int(input("Write a number: "))
    except ValueError:
        print("You must write a number: ")
    else:
        break

try 语句执行。如果抛出异常,except 块将接管,它是 运行。如果没有抛出异常,则执行 else 块。别担心,如果 except 块曾经执行过,else 块将不会被调用。 :)

另外,您应该注意到这个答案被认为更符合 Pythonic,而 Bhargav 的答案可以说更容易阅读和更直观。