如何在“ while”循环中结束“ try”循环?

时间:2018-11-30 06:18:54

标签: python python-3.x

我在如何结束“ try”循环时遇到了麻烦,这是因为我有了“ try”,这是代码:

import time

class exe_loc:
    mem = ''
    lib = ''
    main = ''

def wizard():
    while True:
        try:
            temp_me = input('Please specify the full directory of the memory, usually it will be a folder called "mem"> ' )
            if temp_me is True:
                exe_loc.mem = temp_me
                time.sleep(1)
            else:
                print('Error value! Please run this configurator again!')
                sys.exit()
            temp_lib = input('Please specify the full directory of the library, usually it will be a folder called "lib"> ')
            if temp_lib is True:
                exe_loc.lib = temp_lib
                time.sleep(1)
            else:
                print('Invalid value! Please run this configurator again!')
                sys.exit()
            temp_main = input('Please specify the full main executable directory, usually it will be app main directory> ')
            if temp_main is True:
                exe_loc.main = temp_main
                time.sleep(1)

我尝试通过使用breakpass结束它,甚至将其空出Unexpected EOF while parsing,我在网上搜索,他们说这是由于代码块引起的尚未完成。如果我的代码有误,请告诉我。

顺便说一句,我使用的是python 3,我不知道该问题的具体方式,请问我是否理解。对不起,我英语不好。

编辑:通过删除try可以解决此问题,因为我没有使用它,但是我仍然想知道如何正确结束try循环,谢谢。

2 个答案:

答案 0 :(得分:2)

您还必须使用except语句“捕获”异常,否则尝试没有用。

因此,如果您执行以下操作:

 try:
    # some code here
 except Exception:
    # What to do if specified error is encountered

这样,如果您在try块中的任何地方引发了异常,它都不会破坏您的代码,但会被您的except捕获。

答案 1 :(得分:2)

您的问题不是break,而是您的try子句的总体高级形式。

try需要一个except或一个finally块。您都没有,这意味着您的try子句从未真正完成。因此python一直在寻找下一个比特,直到到达EOF(文件结束)为止,然后抱怨。

python docs进行了更详细的说明,但是基本上您需要:

try:
    do_stuff_here()
finally:
    do_cleanup_here()  # always runs, even if the above raises an exception

try:
    do_stuff_here()
except SomeException:
    handle_exception_here() # if do_stuff_here raised a SomeException

(您也可以同时拥有exceptfinally。)如果您既不需要清理也不需要异常处理,那就更容易了:完全删除try,并将该块直接放在该while True的下面。

最后,作为术语,try不是循环。循环是多次执行的少量代码-循环。 try被执行一次。这是一个“子句”,而不是一个“循环”。

相关问题