1

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?

Community
  • 1
  • 1
n611x007
  • 8,952
  • 8
  • 59
  • 102
  • 4
    The block of lines indented below a statement is called a ["suite"](http://docs.python.org/2/reference/compound_stmts.html). – Martijn Pieters Feb 22 '13 at 17:02
  • I'm having a hard time actually understanding what you're asking about here. Variables introduced in if statements and for loops are part of the local scope if that's what you're asking ... – mgilson Feb 22 '13 at 17:03
  • @mgilson: I didn't mean valid variable naming. I'm trying to talk about the code block, but not sure if that's the right term. I've tried to clarify my question with an example. – n611x007 Feb 22 '13 at 17:07
  • @mgilson but I think the question refers to the fact that `if` and `for` do not create a new local scope, whereas `def` and `class` do. Obviously variables introduced _anywhere_ are part of their local scope unless declared otherwise, but how big of a block that scope is in question. – askewchan Feb 22 '13 at 17:09

2 Answers2

2

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.

Ken Bellows
  • 6,711
  • 13
  • 50
  • 78
2

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. :)

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • I suspect not using the word "block" is to avoid confusing people familiar with block-scoped languages. Not that this helps all that much. – Wooble Feb 22 '13 at 17:34