在Python的尝试中。。。否则。。。子句,如果try失败,为什么要解析else子句?

2024-09-28 05:26:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一个问题。。。否则。。。我正在测试是否使用try设置了一个变量。如果没有设置,我只想继续循环。如果已经设置了变量,我想运行else部分。然而,Python抛出了一个抖动,因为它试图在else部分执行操作,而失败是因为变量尚未设置。有点像第二十二条军规?有别的解决办法吗?你知道吗

代码:

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 ...

Tags: 代码intestnoneforiflineelse
3条回答

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

首先,在代码中不会出现异常,因为测试变量是创建的。由于从来没有异常,因此始终会执行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

浏览你的代码。。。我将把它简化为:

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

相关问题 更多 >

    热门问题