[英]Are indented code under an `if` and a `def` both called blocks in Python?
In Python, keywords like def
, class
introduce a new scope . 在Python中, def
, class
等关键字引入了一个新的范围 。 Others, like if
or for
do not - they use the scope of the enclosing code. 其他人,比如if
或for
not - 他们使用封闭代码的范围。 (The scope resolution is explained in Short Description of the Scoping Rules? .) (范围解析在范围规则的简短描述中进行了解释? )
What are the proper terminology for the code lines "indented under" these two, different kind of keywords? 对于这两种不同类型的关键字,“缩进”代码行的正确术语是什么?
Example: 例:
def foo():
do_bar() # indent type 1
do_another_bar() # indent type 1
Example 2: 例2:
if True:
do_something() # indent type 2
do_more_things() # indent type 2
Are both indent "type 1" and "type 2" called " blocks " of code? 缩进“类型1”和“类型2”都称为代码“ 块 ”吗?
Generally speaking, yes, any section of text indented under a <keyword-clause>:
is called a "block". 一般来说,是的,在<keyword-clause>:
下缩进的任何文本部分都称为“块”。
The same is true of any section of text within curly braces in C/C++/Java/JavaScript/Perl/PHP/etc. C / C ++ / Java / JavaScript / Perl / PHP / etc中花括号内的任何文本部分也是如此。 Indentation is Python's curly-braces. 缩进是Python的大括号。
The grammar for a compound statement in Python defines the indented block of code as a "suite." Python中复合语句的语法将缩进的代码块定义为“套件”。 For example: 例如:
if_stmt ::= "if" expression ":" suite
( "elif" expression ":" suite )*
["else" ":" suite]
So, in a practical example like: 所以,在一个实际例子中:
if True:
print "It's true!"
the line containing the print statement (and any other lines within that level of indentation) would be a suite. 包含print语句的行(以及该缩进级别内的任何其他行)将是一个套件。
If it helps to think of each level of indentation as a code block, fine. 如果将每个级别的缩进视为代码块有帮助,那很好。 However, the Python grammar calls it a suite. 但是,Python语法将其称为套件。 :) :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.