Python

From LQWiki
Jump to navigation Jump to search

Python is an object-oriented, interpreted language created by Guido van Rossum and named after the BBC's comedy "Monty Python's Flying Circus". Many people choose to liken it to Perl, Tcl or Java for whatever reason - most probably because it has the huge capabilities of Perl, the graphical ease of Tcl and a clean object-oriented syntax like Java. Although object-oriented in syntax, Python does not force you to use this idiom and thus you can program procedurally just as well. The language supports C/C++ extensions and even allows you to write such things in Java through Jython.

First start

One of the first problems that newcomers run into is that python modules are missing. This looks like this:

Traceback (most recent call last):
  File "./myscript.py", line 16, in ?
    import mymodule
ImportError: No module named mymodule

The man page states the python modules should be installed in

${exec_prefix}/lib/python<version>

So just copy mymodule.py to your module path:

cp mymodule.py $(which python | sed "s/python//"|sed "s/bin/lib/")$(python -V 2>&1| sed "s/P/p/" | sed "s/ //" | sed "s/.[0-9]*$//")

Syntax

One of the primary differences between Python and other descendents of the C language is the use of indentation whitespace to determine scope. This is best demonstrated with an example:

if spam == 1:
    # this code is considered inside
    # the scope of the if statement
# this code is considered outside
# the scope of the if statement

This means that no scope-closing syntactical construction is necessary; the fact that the indentation level is restored to that of the beginning statement means that the block has been closed. Consequently, it is important that the indentation in a program remain consistent throughout.

Hello world

The canonical hello world program in Python shows how simple this language is:

print("Hello, world!")

See also

A great series of articles featuring Bruce Eckel (author of Thinking in C++ and Thinking in Java) focusing mainly on why he now prefers Python to Java or C++.