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

社会主义新天地 提交于 2019-12-06 11:36:13

问题


I am running a code that might get an error, but I want to run it as long as there is no error.

I thought about something like that:

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

回答1:


You were quite near

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

To know more about exception handling, refer the documentation




回答2:


As an addition to Bhargav's answer, I figured I would mention one other option:

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

The try statement executes. If an exception is thrown, the except block takes over, and it's run. The else block is executed if no exception is thrown. And don't worry, if the except block ever executes, the else block won't be called. :)

Also, you should note that this answer is considered to be more Pythonic, while Bhargav's answer is arguably easier to read and more intuitive.



来源:https://stackoverflow.com/questions/29779695/how-to-run-a-while-loop-as-long-as-there-is-no-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!