简体   繁体   中英

Are indented code under an `if` and a `def` both called blocks in Python?

In Python, keywords like def , class introduce a new scope . Others, like if or for do not - they use the scope of the enclosing code. (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:

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?

Generally speaking, yes, any section of text indented under a <keyword-clause>: is called a "block".

The same is true of any section of text within curly braces in C/C++/Java/JavaScript/Perl/PHP/etc. Indentation is Python's curly-braces.

Compound Statements and Suites

The grammar for a compound statement in Python defines the indented block of code as a "suite." 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.

If it helps to think of each level of indentation as a code block, fine. However, the Python grammar calls it a suite. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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