尝试与if语句冲突相邻的except子句

时间:2013-11-14 19:43:50

标签: python exception if-statement exception-handling try-catch

让我用一些演示代码解释这个问题:

 def my_func:
    if not a:
        #operations A here.
    try:
        #operations B here. 
    except:
        #operations C here.

这里的问题是try-except子句似乎包含在if语句中。只有当“not a”为True时,才会执行try-except子句,否则它们永远不会被执行。

我尝试在try-except子句之前缩小一些缩进空间,如下所示:

def my_func:
    if not a:
        #operations A here.
try:
    #operations B here. 
except:
    #operations C here.

现在一切看起来都像try-except一样用if语句独立执行。

非常感谢任何解释。

1 个答案:

答案 0 :(得分:1)

您的缩进中有混合制表符和空格,这导致解释程序误解缩进级别,认为try高一级:

>>> if True:
...     if True:   # indentation with 4 spaces. Any number will do
...     a = 1      # indentation with a tab. Equals two indents with spaces
...     else:      # indentation with 4 spaces
...     a = 2
... 
>>> a   # as if the "a = 1" was inside the second if
1

要检查这是否是问题,请通过python -tt启动程序,如果找到混合标签和空格,则会引发错误。另请注意,使用python3时,会自动使用-tt选项运行,不允许混合制表符和空格。

相关问题