You are here: Home > Dive Into Python > Your First Python Program > Indenting Code | << >> | ||||
Dive Into PythonPython from novice to pro |
Python functions have no explicit begin or end, and no curly braces to mark where the function code starts and stops. The only delimiter is a colon (:) and the indentation of the code itself.
Example 2.5. Indenting the buildConnectionString Function
def buildConnectionString(params): """Build a connection string from a dictionary of parameters. Returns string.""" return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
Code blocks are defined by their indentation. By "code block", I mean functions, if statements, for loops, while loops, and so forth. Indenting starts a block and unindenting ends it. There are no explicit braces, brackets, or keywords. This means that whitespace is significant, and must be consistent. In this example, the function code (including the doc string) is indented four spaces. It doesn't need to be four spaces, it just needs to be consistent. The first line that is not indented is outside the function.
Example 2.6, “if Statements” shows an example of code indentation with if statements.
Example 2.6. if Statements
def fib(n): print 'n =', n if n > 1: return n * fib(n - 1) else: print 'end of the line' return 1
After some initial protests and several snide analogies to Fortran, you will make peace with this and start seeing its benefits. One major benefit is that all Python programs look similar, since indentation is a language requirement and not a matter of style. This makes it easier to read and understand other people's Python code.
Python uses carriage returns to separate statements and a colon and indentation to separate code blocks. C++ and Java use semicolons to separate statements and curly braces to separate code blocks. |
Further Reading on Code Indentation
- Python Reference Manual discusses cross-platform indentation issues and shows various indentation errors.
- Python Style Guide discusses good indentation style.
<< Everything Is an Object |
| 1 | 2 | 3 | 4 | 5 | 6 | |
Testing Modules >> |