【问题标题】:Try except clause adjacent to if statement conflict尝试与 if 语句冲突相邻的 except 子句
【发布时间】:2013-11-28 00:10:24
【问题描述】:

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

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

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

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

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

现在一切似乎都可以正常工作,因为 try-except 是使用 if 语句独立执行的。

任何解释都非常感谢。

【问题讨论】:

  • 样本中的缩进看起来是正确的。你应该向我们展示一些真实的代码。
  • 您可能混合了制表符和空格,导致解释器认为缩进不同。请尝试使用python -tt 运行程序,python 可能会抱怨混合制表符和空格。在这种情况下,始终使用空格而不是制表符来修复缩进。我唯一可以确定的是 if 问题不是这种混合,并且 if 代码确实具有您显示的相同结构,那么肯定还有其他问题你的代码,所以你应该考虑提供一个我们可以运行的例子。
  • 第一个块按预期工作:见ideone.com/yLahE2
  • @bakuriu 请发表您的评论作为答案。在这种情况下,我似乎确实将制表符与空格混合在一起。

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


【解决方案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 选项运行,不允许混合制表符和空格。

【讨论】:

    猜你喜欢
    • 2019-08-05
    • 2012-08-31
    • 2022-01-12
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    相关资源
    最近更新 更多