与if语句冲突相邻的Try except子句

2024-04-19 18:44:58 发布

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

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

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

这里的问题是try-except子句似乎包含在if语句中。只有当“nota”为真时,try-except子句语句才会被执行,否则就永远不会被执行。你知道吗

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

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

现在,除了使用if语句独立执行之外,所有操作都像try一样工作。你知道吗

任何解释都非常感谢。你知道吗


Tags: 代码ifheremydefnot空间语句
1条回答
网友
1楼 · 发布于 2024-04-19 18:44:58

您在缩进中混合了制表符和空格,这会导致解释器误解缩进级别,认为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选项,不允许混合制表符和空格。你知道吗

相关问题 更多 >