python使用缩进表示语句块_为什么python使用缩进来定义条件语句的块?

它或多或少是硬连接到lexer中的-任何跟在:后面的都被认为是块语句,如果之后有新行,那么它必须至少缩进一个空格。在

PEP 8对Python的正式样式指南提供了一些清晰的说明。简而言之,缩进使代码更具可读性。在The indentation levels of consecutive lines are used to generate

INDENT and DEDENT tokens, using a stack, as follows.

Before the first line of the file is read, a single zero is pushed on

the stack; this will never be popped off again. The numbers pushed on

the stack will always be strictly increasing from bottom to top. At

the beginning of each logical line, the line’s indentation level is

compared to the top of the stack. If it is equal, nothing happens. If

it is larger, it is pushed on the stack, and one INDENT token is

generated. If it is smaller, it must be one of the numbers occurring

on the stack; all numbers on the stack that are larger are popped off,

and for each number popped off a DEDENT token is generated. At the end

of the file, a DEDENT token is generated for each number remaining on

the stack that is larger than zero.

sinepython使用堆栈来保证特定块的缩进级别是一致的,没有缩进将破坏lexer,并导致Python代码不被解释。在

lexer的灵活性也允许这样做(但不要这样做,否则Python程序员会一直鄙视你,直到最后):def foo(n):

for i in range(0, 10):

print i, i+1

i = 0

while i < 10:

print i

print i - 1

print i + 1

哦,如果你有太多的嵌套语句,也许你应该考虑重构你的代码,使其读得更清楚,并减少代码的复杂性?在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值