在Python的try...else...子句中,为什么在try失败时解析else子句?

In Python's try... else... clause, why is the else claused parsed if try fails?

我在使用 try...else... 时遇到问题 我正在测试是否已使用 try 设置了一个变量。如果尚未设置,我只想继续循环。如果已设置变量,我想 运行 else 部分。但是,Python 会抛出一个不稳定的问题,因为它试图在 else 部分执行操作,但由于尚未设置变量而失败。有点像第 22 条军规?有替代解决方案吗?

代码:

test = None
for num, line in enumerate(dataFile, 0):
    if myString in line:
        test = num
    try:
        test
    except:
        pass
    else:
        if (num - test) <= 58:
            ... do something ...

尝试使用 if 语句来检查 test 是否以 NoneType 以外的形式存在。

test = None
for num, line in enumerate(dataFile, 0):
    if myString in line:
        test = num
    if test is not None:
        if (num - test) <= 58:
            # do something

或者完全删除第二个 if 语句。

for num, line in enumerate(dataFile, 0):
    if (myString in line) and ((num - test) <= 58):
        # do something

遍历您的代码...我会将其简化为:

foo = None

if foo:
    print 'Foo is not None'   # We never run this
try:
    foo    # This doesn't do anything, so this segment of the try / except will always end here
except:
    print 'The try segment did not raise an error'   # We also never get here
else:
    print 'Foo is none'   # We end up here because Foo is none, so this will print

本质上...您的 try / except 子句与 if / then 语句无关。这是因为你的缩进。

因此在您的示例中 if mystring not in line 那么 else 语句中的所有内容都将执行。

您可以更轻松地检查没有像这样设置的变量:

if not foo:
    # Do something with foo if it doesn't exist
else:
    # Continue running your loop since foo was set

首先,在您的代码中不会出现异常,因为已创建测试变量。因为你永远不会有例外,所以总是会执行 else 子句(这就是 try/except 子句中的 else 的意思:运行 这部分代码,如果这里没有引发异常的话)。

如果你只是想知道是否设置了一个变量,如果它不只是继续循环,你可以这样做:

# ...
for num, line in enumerate(dataFile, 0):
    # ...
    try: 
        test
    except NameError:
        # here you say 'skip the rest of loop in case of test was not setted'
        continue
   # here the rest of the code

对于您的情况,也许更简单的方法是:

for num, line in enumerate(dataFile, 0):
    if myString in line:
        # in your code, if myString in line, test = num. So, num - test will allways be < 58 when myString in line

        # do something