This page gives a short introduction into the Python programming language, tailored to first-time users of the Python-bindings of opals-modules. Most information given on Python is based on the documentation given on the official Python website.
While the reference implementation (a.k.a. CPython) is written in C, there exist implementations in several different languages, including Java and C#. CPython today is available in 2 production versions: as Python 3 is backwards-incompatible with Python 2, and more third-party software is compatible with the latter (opals can be used with both), installing Python 2 still seems to be advisable. Ready-to-use installers for CPython are available for download that allow for extending Python later on (for that purpose, consider the package pip). However, one may opt for pre-packaged Python distributions that already come with an extended set of features. Among these, pythonxy shall be mentioned, which bundles some of the most powerful Python modules, including
After installation, the Python interpreter may directly be invoked from a command prompt. However, several comprehensive integrated development environments are available, offering symbolic debuggers, code completion, project management, and more. Among them, PyScripter and Spyder shall be mentioned.
Invoking the Python interpreter and subsequently importing the module "this", reveals a compact formulation of the philosophy behind Python:
Comments are introduced by a hash sign (#
) and extend until the end of line.
int:
signed integer, 4 bytesboolean:
a subtype of int
, with the predefined constants True
, False
long:
integer with unlimited precisionfloat:
real number, typically 8 bytescomplex:
complex number consisting of 2 floats
All common arithmetic operators are supported, which adhere to their common precedence:
Collections combine into a common container zero or more objects, which may themselves be collections. Note that collections in Python do not restrict the contained elements to be of a common data type.
str:
String literals are immutable (i.e. constant after construction) and are to be enclosed in either single or double quotes. The escape character is the backslash (
). When dealing with e.g. file paths containing backslashes, turn escaping off by preceding the string literal with an 'r' ("raw").unicode:
In contrast to p str, whose character set is limited to the code page in use, p unicode strings may contain practically any character of the world's writing systems. Unicode strings are preceded with a p 'u'. Kindly note that opals modules currently do not support p unicode.list:
Lists are mutable objects - that is, their size and contents may be changed after construction. Lists are constructed using square brackets, with the items separated by commas.tuple:
Tuples are immutable objects and are constructed by the comma operator, with or without enclosing parentheses.Sequence types share many common operations:
x in s
: True
if an item of s
is equal to x
, else False
x not in s
: False
if an item of s
is equal to x
, else True
s + t
: the concatenation of s
and t
s * n, p n * s
: n
shallow copies of s
concatenateds[i]
: ith
item of s
, where indexing is zero-baseds[i:j]
: slice of s
from i
to j
s[i:j:k]
: slice of s
from i
to j
with step k
len(s)
: length of s
min(s)
: smallest item of s
max(s)
: largest item of s
s.index(i)
: index of the first occurence of i
in s
s.count(i)
: total number of occurences of i
in s
Strings support many functions for case conversion, searching, etc. Mutable sequence types support insertion, removal and sorting of elements via respective functions. A few examples:
Set types constitute unordered collections of distinct objects. Two set types are defined:
set
mutablefrozenset
immutableSet types may be constructed by a comma-separated list of elements within curly braces (beginning with Python 2.7) and support the set operations union
, intersection
, difference
, symmetric_difference
.
Mapping types map hashable objects to arbitrary values (all of Python's immutable built-in types are hashable). A single mapping type is built into Python: dict
. dict
may be initialized with a comma-separated list of key:value pairs within curly braces:
Python variables are typed at the moment when a value is assigned, meaning that
Variables declared in Python are generally only handles that refer to an object. Assigning one variable to another may not copy a value, but increase the reference count of the object that both variables subsequently point to. In CPython, this does not hold for numeric types, but e.g. for sequences.
However, comparing variables using operator ==
is done by-value: variables are guaranteed to compare equal if their values are identical, regardless of whether they refer to the same object.
Code blocks group together a number of statements that shall be executed in order. In Python, code blocks must be marked by indentation (not by e.g. parentheses). This results in compact code, but may lead to problems if tabulators and space characters are both used for indentation (e.g. if Python code is read from file): following certain rules, the Python interpreter replaces tabulators with 1 to 8 blanks. That's why a mixture of tabulators and space characters in the same file is inadvisable. Nested code blocks, as e.g. in function definitions and in the branches of conditional statements, must be initiated with a colon (:).
Amongst others, program flow may be controlled using if
, for
, and while
statements. If a sequence type is to be filled successively in a loop, the type must be pre-defined before the loop.
List comprehensions provide a concise way to create lists. They consist of an expression followed by a for
clause, then zero or more for
or if
clauses:
As stated above, list comprehensions may be nested, allowing for processing elements of nested lists (as returned from opals modules):
Like e.g. C, Python features a ternary conditional operator, which evaluates to one of its branches, depending on the result of evaluating its condition. The order in which the branches are specified in Python, however may seem surprising:
True
, followed by the keyword if
,else
,False
Function definitions start with the keyword def
, followed by
:), andAdjacent to the argument names, default values may be specified, separated by an equal sign (=
). These may be omitted in function calls. Additionally, any function argument value may be specified by argument name. Values may be returned from functions using the keyword return
.
Error handling in Python is performed using exceptions: exceptions are (small) objects that carry information about the occurred error via their type, and their string representation (error message). Division by zero, for example, results in a ZeroDivisionError
to be raised, which is one of Python's predefined exception types:
Raising an exception generally makes the interpreter abort execution and return to the prompt or the calling application. However, exceptions may be handled programmatically: when iterating over a sequence, the exception may e.g. be printed on the screen, and looping may be continued.
OPALS exposes its own exception types (see opals::Exceptions) that are derived from Python's Exception
, which may thus be handled specifically.
Anything not built into Python must be imported in order to be accessible - this holds true for opals modules and types, but also for those of the Python standard library. The import may be conducted e.g. by using the command import
. Depending on the use of this command, all, some, or no prefixes must be specified to access the imported names: whatever directly follows the command import
. One or more names following import
may either be specified explicitly (separated by commas), or any name defined in a module may be imported using the wildcard *
. By suffixing the import
-command with as
, aliases may be defined.
opals modules provide most help on data types provided in this html-help also on-line in the Python interpreter, which is shown using the Python-built-in function help
. This prints e.g. a module's description, together with all its methods, again with respective descriptions. In addition to the method's meaning, a method's description informs about the number and types of arguments and the type of the return value, if any. Note that the internally used C++ - data types are given.
If variable values shall e.g. be preserved for the next Python session, the module cPickle comes in handy, as it allows for converting most Python types (including those exposed by opals) to/from a byte string and (re-)storing them to/from file: