In PythonLanguage, there is no need for braces because the indentation level provides the grouping. For example:
names = ['michael', 'john', 'eric'] for name in names: print "\n" + name print " contains " print name.size() print " letters." print "\nDone."Everything indented under the for is part of the for loop. Outdented code is not. Easy as pie, yes?
Newcomers to PythonLanguage sometimes find this confusing, but that is mostly, I suspect, because it's different than the way C++ or Java does it. People who use Python for a while tend to be neutral or positive about this feature of the language.
There are arguments for and against this, and they rage all over programmer groups on the web in general. Basically it boils down to these.
For:
Why then doesn't python disallow sequences of spaces (>1 space) that are outside comments? Sounds like it should be a compiler error to have consecutive spaces.
Note that the grouping implied by the indentation does not necessarily equate to scope. The scoping rules of Python are rather simpler than that:
names = ['michael, 'john', 'eric'] for name in names: hello = 'Ni!' # fresh variable inside the indented loop print hello, nameOutside of the for loop, the loop variable name still exists, with the final loop value 'eric'. The hello variable still exists as well; its value is 'Ni!'. If these were lines in a function, these variables would have function scope. However, executing the same code interactively:
>>> names = ['john', 'michael', 'eric'] >>> for name in names: ... hello = 'Ni!' ... # second newline to terminate expression interactively >>> print hello, name >>> dir()dir() after the loop lists hello, name, and names as objects available in the current scope, even though name is the looping variable and hello was created inside the indented loop, because all of these variables are now effectively in module scope.
Note that whether a variable is function-local or global is resolved when the function is compiled, and takes effect for all references to that variable. For example:
>>> var = 42 >>> def incrementer(): ... print var ... var += 1 ... print var ... # second newline to terminate expression interactively >>> incrementer()This will throw an exception at the first print statement, because in the incrementer function var is treated as a local variable even before it has been assigned to.
Languages where IndentationEqualsScope:
See also: AlwaysUseBracesOnIfThen, SyntacticallySignificantWhitespaceConsideredHarmful, PythonWhiteSpaceDiscussion
NestedScopes, LexicalScoping, DynamicScoping