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:
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:
Statements can span more than one line if they are collected within braces (parentheses (), square brackets [], or curly braces {}). Normally parentheses are used. When spanning lines within braces, indentation doesn't matter; the indentation of the initial bracket is used to determine which code section the whole statement belongs to. The following example shows a single variable having to span multiple lines due to the length of the parameters:
tank1 = tank.Tank(
"Tank 1",
level=36.0,
fluid_density=DENSITY,
spec_gravity=SPEC_GRAVITY,
outlet_diam=16,
outlet_slope=0.25
)
tank1 is the variable, and everything to the right of the equal sign is assigned to tank1. While Python allows the developer to write everything within the parentheses on one line, the preceding example has separated each parameter into different lines for clarity.
The Python interpreter recognizes that everything within the parentheses is part of the same object (tank1), so spreading the parameters across multiple lines doesn't cause a problem.
String statements (text) can also be multiline if you use triple quotes. For example, the following screenshot demonstrates a long block of text that is spread over multiple lines:
Triple quote line spanning
When the variable containing the text is directly called (line 10 in the preceding screenshot), Python returns the raw text, including the \n symbol which represents a newline character; it tells the system where a new line starts and the old one ends. However, when the print() function is called in line 11, the text is printed as it was originally entered.
Like many other programming languages, Python has built-in data types that the programmer uses to create a program. These data types are the building blocks of the program. Depending on the language, different data types are available. Some languages, notably C and C++, have very primitive types; a lot of programming time is spent simply combining these primitive types into useful data structures.
Python does away with a lot of this tedious work. It already implements a wide range of types and structures, leaving the developer more time to actually create the program. Having to constantly recreate the same data structures for every program is not something to look forward to.
Python has the following built-in types:
- Numbers
- Strings
- Lists
- Dictionaries
- Tuples
- Files
- Sets
- Databases
In addition, functions, modules, classes, and implementation-related types are also considered built-in types, because they can be passed between scripts, stored in other objects, and otherwise treated like the other fundamental types.
Naturally, you can build your own types if needed, but Python was created so that very rarely will you have to roll your own. The built-in types are powerful enough to cover the vast majority of your code and are easily enhanced.
It was mentioned previously that Python is a dynamic typed language; that is, a variable can be used as an integer, a float, a string, or whatever. Python will determine what is needed as it runs. The following screenshot shows how variables can be assigned arbitrarily. You can also see that it is trivial to change a value, as shown in line 16:
Dynamic typing
Other languages often require the programmer to decide what the variable must be when it is initially created. For example, C would require you to declare x in the preceding program to be of type int and y to be of type string. From then on, that's all those variables can be, even if, later on, you decide that they should be a different type.
That means you would have to decide what each variable will be when you started your program; that is, deciding whether a number variable should be an integer or a floating-point number. Obviously, you could go back and change them at a later time, but it's just one more thing for you to think about and remember. Plus, any time you forgot what type a variable was and you tried to assign the wrong value to it, you would get a compiler error.
Python also has a difference between expressions and statements. In Python, an expression can contain identifiers (names), literals (constant values of built-in types), and operators (primarily arithmetic-looking symbols, but can be other items, such as [], (), or other symbols). Expressions can be reduced to a derived value, much like solving a math equation.
Statements, on the other hand, are everything that can make up a line (or multiple lines) of code; that...