首页 > 解决方案 > 如何在“while”循环中结束“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)

我试着用break,结束它pass,我什至把它留空了我得到的是Unexpected EOF while parsing,我在网上搜索,他们说这是代码块没有完成时造成的。如果我的代码有错误,请告诉我,谢谢。

顺便说一句,我使用的是 python 3,我不知道如何更具体地回答这个问题,如果你不明白,请问我。对不起我糟糕的英语。

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

标签: pythonpython-3.x

解决方案


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

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

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

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


推荐阅读