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

时间:2015-03-10 17:39:22

标签: python try-catch

我遇到了一个问题,尝试...其他...我正在测试使用try设置了一个变量。如果尚未设置,我只想继续循环。如果已设置变量,我想运行else部分。但是,Python会因为尝试在else部分执行操作而失败,因为该变量尚未设置,因此会出现抖动。有点像Catch-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 ...

3 个答案:

答案 0 :(得分:2)

遍历您的代码......我将对此进行一些简化:

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

答案 1 :(得分:1)

尝试使用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

答案 2 :(得分:1)

首先,在您的代码中,您将不会有异常,因为已创建测试变量。因为你从来没有异常,所以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