繁体   English   中英

不同的缩进在python中没有错误

[英]Different indentation no error in python

password = raw_input("Enter password: ")
if password == "1234":
  print "You logged in correctly!"
else:
    print "GTFO"

虽然我给出了不同的缩进代码工作正常但我无法弄明白。

它不会被标记为IndentationError,正则任何语句块必须至少有1个缩进空间

这里你的ifelse是两个不同的块,所以它总是缩进,所以解释器不会抛出任何错误

if True:
 print 
elif True:
  print 
elif True:
   print 
elif True:
     print 
else:
         print

这将没有任何问题

但是,如果我尝试以下操作,我将得到IndendationError

if True:

    print ""
      print ""  # has different Indentation
    print ""

Python文档解释了缩进。 这是一个相关的摘录:

在每个逻辑行的开头,将行的缩进级别与堆栈的顶部进行比较。 如果它是平等的,没有任何反应。 如果它更大,则将其推入堆栈,并生成一个INDENT令牌。 如果它更小,它必须是堆栈上出现的数字之一

在您的代码中,由于缩进级别大于堆栈的顶部(为0 ),因此将其视为单个缩进。 else:行从堆栈顶部弹出2 ,因此解释器没有先前缩进级别为2内存。 它只知道它高于0

在块中开始混合缩进时会出现问题:

def foo():
    if True:
        return True
      return False  # Is this part of the if statement or not?

当解析器到达return False ,堆栈包含[4, 8] 下一行的缩进为6 ,它不包含在堆栈中,因此会生成IndentationError

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM