Python is based on the C programming language and is written in C, so much of the format Python uses will be familiar to C and C++ programmers. However, it makes life a little easier because it's not made to be a low-level language (it's difficult to interact heavily with hardware or perform memory allocation) and it has built-in "garbage collection" (it tracks references to objects and automatically removes objects from memory when they are no longer referenced), which allows the programmer to worry more about how the program will work rather than dealing with the computer.
Python Syntax
Indentation
Python forces the user to program in a structured format. Code blocks are determined by the amount of indentation used. As you’ll recall from the Comparison of Programming Languages chapter, brackets and semicolons were used to show code grouping or end-of-line termination for the other languages. Python doesn’t require those; indentation is used to signify where each code block starts and ends. Here is an example (line numbers are added for clarification):
x = 1
if x: #if x is true
y = 2
if y: #if y is true
print 'block2'
print 'block1'
print 'block0'
Each indented line demarcates a new code block. To walk through the above code snippet, line 1 is the start of the main code block. Line 2 is a new code section; if “x” has a value not equal to 0, then indented lines below it will be evaluated. Hence, lines 3 and 4 are in another code section and will be evaluated if line 2 is true. Line 5 is yet another code section and is only evaluated if line “y” is not equal to 0. Line 6 is part of the same code block as lines 3 and 4; it will also be evaluated at the same time as those lines. Line 7 is in the same section as line 1 and is evaluated regardless of what any indented lines may do.
You'll notice that compound statements, like 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.
A quick note: the act of saying “x = 1” is assigning a value to a variable. In this case, “x” is the variable; by definition its value varies. That just means that you can give it any value you want; in this case the value is “1”. Variables are one of the most common programming items you will work with because they are what store values and are used in data manipulation.
Multiple Line Spanning
Statements can span more than one line if they are collected within braces (parenthesis "()", square brackets "[]", or curly braces "{}"). Normally parentheses are used. When spanning lines within braces, indentation doesn't matter; the indentation of the initial bracket used to determine which code section the whole statement belongs to. String statements can also be multi-line if you use triple quotes. For example:
Generic Code Example:
>>> big = """This is
... a multi-line block
... of text; Python puts
... an end-of-line marker
... after each line. """
>>>
>>> big
'This is\012a multi-line block\012of text; Python puts\012an end-of-line marker\012after each line.'
Note that the \012 is the octal version of \n, the “newline” indicator. The ellipsis (...) above are blank lines in the interactive Python prompt used to indicate the interpreter is waiting for more information.
Python Object Types
Like many other programming languages, Python has built-in data types that the programmer uses to create his 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 simply used up to combine 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. Trust me, this is one of the things I hated when I was learning C/C++; 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, and files. 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. We'll finish up this section by talking about numbers; we'll cover the others in later chapters.
Before I forget, I should mention that Python doesn't have strong coded types; 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. See below:
Generic Code Example:
>>> x = 12
>>> y = "lumberjack"
>>> x
12
>>> y
'lumberjack'
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 above 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 have to decide what each variable will be when you start your program, i.e. 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, anytime you forget what type a variable is and you try to assign the wrong value to it, you would get a compiler error.
Python Numbers
Python can handle normal long integers (max length determined based on the operating system, just like C), Python long integers (max length dependent on available memory), floating point numbers (just like C doubles), octal and hex numbers, and complex numbers (numbers with an imaginary component). Here are some examples of these numbers:
Python has the normal built-in numeric tools you'd expect: expression operators (*, >>, +, <, etc.), math functions (pow, abs, etc.), and utilities (rand, math, etc.). For heavy number-crunching Python has the Numeric Python extension that has such things as matrix data types. If you need it, it has to be installed separately. It’s heavily used in science and mathematic settings, as it’s power and ease of use make it equivalent to Mathematica, Maple, and MatLab.
This probably doesn’t mean much to non-programmers, but the expression operators found in C have been included in Python, however several of them are slightly different. Logic operators are spelled out in Python rather than using symbols, e.g. logical AND is represented by "and", not by "&&"; logical OR is represented by "or", not "||"; and logical NOT uses "not" instead of "!". More information can be found in the Python documentation.
Operator level-of-precedence is the same as C, but using parenthesis is highly encouraged to ensure the expression is evaluated correctly and enhance readability. Mixed types (float values combined with integer values) are converted up to the highest type before evaluation, i.e. adding a float and an integer will cause the integer to be changed to a float value before the sum is evaluated.
Following up on what I said earlier, variable assignments are created when first used and do not have to be pre-declared like in C.
Generic C++ Example:
int a = 3; //inline initialization of integer
float b; //sequential initialization of floating point number
b = 4.0f;
Generic Python Example:
>>>a = 3 #integer
>>>b = 4.0 #floating point
As you can see, "a" and "b" are both numbers but Python can figure out what type they are without being told. Also, you'll note that comments in Python are set off with a hash/pound sign (#) and are used exactly like the "//" comments in C++ or Java.
That's about it for numbers in Python. It can also handle bit-wise manipulation such as left-shift and right-shift, but if you want to do that, then you'll probably not want to use Python for your project. As also stated, complex numbers can be used but if you ever need to use them, check the documentation first.