Before we get too far into this chapter, we really need to cover the most obvious and special feature of Python: indentation. Python forces the user to program in a structured format. Code blocks are determined by the amount of indentation used; this is frequently referred to as "white space matters". In many other C-based languages, brackets and semicolons are used to show code grouping or end-of-line termination. Python doesn't require those; indentation is used to signify where each code block starts and ends. In this section is an example of how white space works in Python (line numbers are added for clarification). The following code shows how white space is significant:
1 x = 1 2 if x: # if x is True... 3 y = 2 # process this line 4 if y: # if y is True... 5 print("x = true, y = true") # process this line 6 else: # if y is False... 7 print("x = true, y = false") # process this line 8 print("x = true, y = unknown") # if x is True, process this line as well 9 else: # if x is False... 10 print("x = false") # process this line
Each indented line demarcates a new code block. To walk through the preceding code snippet, line 1 is the start of the main code block. Line 2 is a new code section; if x has a value that is true, then indented lines below it will be evaluated. In Python, true can be represented by the word true, any number other than 0, and so on. Hence, lines 3 and 4 are in another code section and will be evaluated only if line 2 is true.
Line 5 is yet another code section and is only evaluated if y is not a false value. Line 6 is part of the same code block as lines 3 and 4; it will also be evaluated in the same block as those lines. Line 9 is in the same section as line 2 and is evaluated regardless of what any other indented lines may do; in this case, this line won't do anything because line 2 is true.
In case that is confusing, the following diagram shows a flowchart of the logic for the previous example. Note that if line 2 is No (the first diamond decision icon), the program logic immediately jumps to line 10 and the program ends. Only if variable X is True will any of the indented lines be evaluated:
You'll notice that compound statements, such as the if comparisons, are created by having the header line followed by a colon (:). The rest of the statement is indented below it. The biggest thing to remember is that indentation determines grouping; if your code doesn't work for some reason, double-check which statements are indented. Some development environments allow you to toggle vertical lines that make it easier to check indentation.
The following screenshot is an example of running the program in the preceding example. Notice that, since both x and y are not equal to zero or another false-type value, the if true statements are printed: