Python is a modern, general-purpose, object-oriented, high-level programming language.

General characteristics of Python:

#General-characteristics-of-Python:
  • clean and simple language: Easy-to-read and intuitive code, easy-to-learn minimalistic syntax, maintainability scales well with size of projects.
  • expressive language: Fewer lines of code, fewer bugs, easier to maintain.

Technical details:

#Technical-details:
  • dynamically typed: No need to define the type of variables, function arguments or return types.
  • automatic memory management: No need to explicitly allocate and deallocate memory for variables and data arrays. No memory leak bugs.
  • interpreted: No need to compile the code. The Python interpreter reads and executes the python code directly.

Advantages:

#Advantages:
  • The main advantage is ease of programming, minimizing the time required to develop, debug and maintain the code.
  • Well designed language that encourage many good programming practices:
  • Modular and object-oriented programming, good system for packaging and re-use of code. This often results in more transparent, maintainable and bug-free code.
  • Documentation tightly integrated with the code.
  • A large standard library, and a large collection of add-on packages.

Disadvantages:

#Disadvantages:
  • Since Python is an interpreted and dynamically typed programming language, the execution of python code can be slow compared to compiled statically typed programming languages, such as C and Fortran.
  • Somewhat decentralized, with different environment, packages and documentation spread out at different places. Can make it harder to get started.

IPython Notebook

#IPython-Notebook

IPython notebook is an HTML-based notebook environment for Python, similar to Mathematica or Maple. It is based on the IPython shell, but provides a cell-based environment with great interactivity, where calculations can be organized and documented in a structured way.

Python 2 vs. Python 3

#Python-2-vs.-Python-3

Libraries for Python2 and Python3 compatibility:

also see

Variables

#Variables

Variables are simply names which point to any value or object

Loading output library...

Print

#Print

To print a constant or variable:

Strings

#Strings

There are 3 syntaxes for string constants:

Loading output library...
Loading output library...

Important note:

#Important-note:

a Python string is immutable. In other words, it is a constant which cannot be changed in place.

All string operations create a new string.

This is strange for a C developer, but it is necessary for some properties of the language. In most cases this is not a problem.

Lists

#Lists

A list is a dynamic array of any objects.

It is declared with square brackets:

Loading output library...

List Comprehension

#List-Comprehension

Tuples

#Tuples

A tuple is similar to a list but it is a fixed-size, immutable array. This means that once a tuple has been created, its elements may not be changed, removed, appended or inserted.

It is declared using parentheses and comma-separated values:

Loading output library...
Loading output library...
Loading output library...

Dictionaries

#Dictionaries

analog Maps in Java.

Loading output library...

Blocks and Indentation (control flow)

#Blocks-and-Indentation-(control-flow)

Blocks of code are delimited using indentation, either spaces or tabs at the beginning of lines. This is one of the main differences of Python over other languages, and that is the main reason why people love it or hate it. ;-)

  • Tip: NEVER mix tabs and spaces in a script, it may result in tricky bugs.
  • From my experience, the safest solution is to always use 4-spaces indents, never tabs. (because each editor may convert tabs either to 2, 4 or 8 spaces)

IF / ELIF / ELSE:

#IF-/-ELIF-/-ELSE:

a=1 while a<10: print a a += 1

a python "for loop" is a foreach loop

More about control flow keywords: http://docs.python.org/tutorial/controlflow.html

Functions

#Functions

A function is defined using the "def" keyword

Functions are first-class citizen

Unnamed functions (lambda function)

#Unnamed-functions-(lambda-function)

In Python we can also create unnamed functions, using the lambda keyword:

Loading output library...
Loading output library...

Script Arguments

#Script-Arguments

It is necessary to import modules from the standard library:

Files

#Files

Open a file for reading

Classes

#Classes

Classes are the key features of object-oriented programming. A class is a structure for representing an object and the operations that can be performed on the object.

In Python a class can contain attributes (variables) and methods (functions).

A class is defined almost like a function, but using the class keyword, and the class definition usually contains a number of class method definitions (a function in a class).

  • Each class method should have an argument self as its first argument. This object is a self-reference.

  • Some class method names have special meaning, for example:

Note that calling class methods can modifiy the state of that particular class instance, but does not effect other class instances or any global variables.

That is one of the nice things about object-oriented design: code such as functions and related variables are grouped in separate and independent entities.

Exceptions

#Exceptions

In Python errors are managed with a special language construct called "Exceptions". When errors occur exceptions can be raised, which interrupts the normal program flow and fallback to somewhere else in the code where the closest try-except statement is defined.

To generate an exception we can use the raise statement, which takes an argument that must be an instance of the class BaseException or a class derived from it.

A typical use of exceptions is to abort functions when some error condition occurs, for example:

1
2
3
4
5
6
def my_function(arguments):

    if not verify(arguments):
        raise Exception("Invalid arguments")
    
    # rest of the code goes here

To gracefully catch errors that are generated by functions and class methods, or by the Python interpreter itself, use the try and except statements:

1
2
3
4
5
6
try:
    # normal code goes here
except:
    # code for error handling goes here
    # this code is not executed unless the code
    # above generated an error

For example:

To get information about the error, we can access the Exception class instance that describes the exception by using for example:

1
except Exception as e:

Modules

#Modules

One of the most important concepts in good programming is to reuse code and avoid repetitions.

The idea is to write functions and classes with a well-defined purpose and scope, and reuse these instead of repeating similar code in different part of a program (modular programming). The result is usually that readability and maintainability of a program is greatly improved. What this means in practice is that our programs have fewer bugs, are easier to extend and debug/troubleshoot.

Python supports modular programming at different levels. Functions and classes are examples of tools for low-level modular programming. Python modules are a higher-level modular programming construct, where we can collect related variables, functions and classes in a module. A python module is defined in a python file (with file-ending .py), and it can be made accessible to other Python modules and programs using the import statement.

Consider the following example: the file mymodule.py contains simple example implementations of a variable, function and a class:

Futher readings

#Futher-readings