Python is an interpreted language, with dynamic typing, support for object oriented programming and exception handling.
It shares many ideas and some syntax with perl and even has a magic variable called _
very
similar to Perl's $_
. And indeed Python can do many of the same things that Perl can do, for example running the
back end of websites, producing small prototype applications and ad-hoc scripts, up to fully-featured cross-platform applications.
The language is free, and available for a huge variety of platforms with a large standard library base.
Python does have some unique features though, most notably the use of whitespace in programs. In many other languages (including java, C, C++, perl and javascript), whitespace is irrelevant and changing the whitespace doesn't change the meaning of the program. It's standard, and strongly encouraged to use indentation in all these languages to make them easier (for the programmer) to read, but it's not necessary - rather, the indented block is also enclosed in brackets or keywords so that the computer also knows where the start and end are. In Python, the computer uses the indentation too, so the enclosing punctuation isn't necessary.
Overall, the language elements are simple but powerful, and the resulting code is easier to read than Perl. The syntax is fairly terse, making it useful for speedy development of one-off scripts, but offers sophisticated features (like OO and exception handling) to enable more complex projects. Another touted feature is its linkage to other languages, making it possible to call modules written in other languages from Python, and also to call Python code from other languages. It's a young language (created in the 1990s) but one growing strongly in popularity.
Getting python is as simple as searching for "python" in the package manager and pressing "install". The version listed here
with Mandriva LE2005 is python-2.4-5mdk
. After install, we can run python to see the version number:
$ python Python 2.4 (#2, Feb 12 2005, 00:29:46) [GCC 3.4.3 (Mandrakelinux 10.2 3.4.3-3mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
This starts the interactive mode, similar to that of Perl, where you can type in commands and see the results immediately. Unlike Perl's interactive mode, each command is executed immediately, rather than running in a batch at the end, so it's a much better way of trying out commands.
In Mandriva, the python
executable is installed by default in /usr/bin/
which should already be
in the default application path for the shell. If for some reason it's somewhere else on your system you may have to explicitly
specify the path to where python
is, or add this path to your $PATH
shell variable.
So let's try the interactive mode to do some simple stuff:
>>> print "hello from python" hello from python >>> my_variable = 2 >>> print my_variable, my_variable * 2 27 54 >>> my_variable = "now a string" >>> print my_variable, my_variable * 2 now a string now a stringnow a string
Note that Python doesn't require you to define the type of a variable, and doesn't mind when you try to multiply a string by
an integer. It does however complain when you try to add a string to an integer, as you can easily see by experimenting.
This can be stated that Python has dynamic typing (variable names can point to objects of different type at different
times), but also strong typing (conversions aren't carried out automatically). By contrast, java has static typing
(a String
variable can't be made to point to an Integer
), and javascript has dynamic and weak typing.
You can also do a simple for
loop in this console, but make sure you indent the loop code properly:
>>> for i in range(4): ... print i ... 0 1 2 3
Now let's save our commands in a file, so we can run it any time we like. Use an editor (doesn't matter whether it's a graphical one like Kate or a console one like vi, use whatever you prefer) and create a new file called hello.py:
my_array = ['some', 'text', 'in', 'an', 'array'] for start in [0, 1, 2]: my_subarray = my_array[start:start+3] for item in my_subarray: print " " * start + item
After saving this file, we can give it straight to the interpreter:
$ python hello.py some text in text in an in an array
This example shows a pair of for
loops, with examples of array definition and slicing.
Note that the for
loops aren't enclosed using curly braces {} but the opening and
closing points are purely determined by the indentation (using tabs or spaces) of the lines of code.
This is a strange concept for someone used to languages which don't care about whitespace.
In this example, the outer loop gives the start
variable the values 0, 1 and 2 in turn.
Each time round this loop, a slice is made of the array, firstly from 0 to 3, then from 1 to 4, and
finally from 2 to 5. This is a powerful mechanism to extract elements from an array, and can also
be used without a start parameter or without an end, for example my_array[1:]
makes a
new array with all elements from my_array
from position 1 onwards. The position numbers
start at 0 so this means the new array contains all except the one at position 0. The end position
is non-inclusive though, so [0:3]
gives elements 0, 1 and 2.
The inner loop looks at each element in the array slice, and prints out each element with an indentation based on the value of start. This indentation shows another example of the easy way to multiply strings by numbers.
In a similar way to shell scripts and perl, we can
make our hello.py
executable so we don't have to type python <file>
to run it, but just <file>
.
As before, edit the file to include the following line as the first line of the file:
#! /usr/bin/env python
Next we need to give ourselves execute permission for this file:
$ chmod u+x hello.py
and then we can execute it directly:
$ ./hello.py
Python suports a range of features for object oriented programming. You can easily write your own classes, and instantiate multiple instances of them. You can even define multiple classes in the same file, whereas in java each public, top-level class must be saved in a file on its own. This example shows two instances of a simple Fibonacci sequence generator being called, showing that the sequences and their instance numbers are held separately and independently.
class Fibonacci: """Generate a Fibonacci sequence of integers""" def __init__(self): self.a = 0 self.b = 1 def nextNumber(self): c = self.a + self.b self.a = self.b self.b = c return self.a generator1 = Fibonacci() for i in range(1,5): print generator1.nextNumber() generator2 = Fibonacci() for i in range(1,10): print generator1.nextNumber(), " ", generator2.nextNumber()
Here the first 5-element loop requests the first 5 numbers from the instance generator1
and then the second loop
requests 10 numbers from both generator1
and generator2
. Because they are separate objects, their
instance variables are held separately.
Python doesn't come with its own built-in GUI libraries, but you can build cross-platform GUI applications using one of the many add-on libraries. For example there's Tk, an old favourite for use with Tcl, or modern variants such as Gtk and Qt. We saw Qt when writing a simple C++ gui, and a binding layer for Python exists called PyQt.
To add this binding to Mandriva, simply select the package from the repositories - go to "Install Software" from the main
menu, and search for "pyqt" - this should give you PyQt-3.14.1-1mdk
which in turn requires a couple more
packages. Easy as that. (Update: In more recent versions of Mandriva this package is now called python-qt
instead.)
Now to test the library with our first ever Python GUI - as with the C++ example, it doesn't do anything beyond displaying a simple, resizable window with a message (in this case a button which doesn't do anything):
import sys from qt import QApplication, QPushButton app = QApplication(sys.argv) button = QPushButton("Hello from Python", None) app.setMainWidget(button) button.show() app.exec_loop()
Now save this file as pythongui.py
and run it as before using python pythongui.py
. Magically
we get a GUI window with a single, functionless button inside it, although the window resizing, minimizing and closing
is all handled for us already.
This example was taken from the excellent GUI Programming with Python guide, so see there for more details. And see the Qt references for more information, as the PyQt layer is just a thin wrapper to allow Python to access the Qt functions.
The above example works with version 3 of the Qt libraries, but since this was written, version 4 of Qt has been released, and several things have changed. Currently there's a bit of a confusing situation with both libraries in use, but code needs to be ported from version 3 to 4 and all steps of the chain have to match - the Qt Designer has to have the same version as your PyQt interface, and the runtime libraries also need to match. So some care is required getting things to work.
To use the Qt4 GUI, you need to use PyQt4 rather than PyQt, and on Mandriva the associated package is called python-qt4
instead of python-qt
. If you try to run version 3 code with the PyQt4 libraries installed, you'll get errors whenever it tries to do a "from qt import" statement, and the code won't run.
The PyQt4 equivalent of the above code is as follows:
import sys from PyQt4 import Qt app = Qt.QApplication(sys.argv) hello = Qt.QPushButton("Hello from Python") hello.show() app.exec_()
Note the main difference is the import statement, most of the other bits are the same, apart from the final exec_()
command. The result looks just the same as the previous screenshot, just maybe with slightly different styles or decorations.
As mentioned above, you can use the Qt-Designer tool to draw your GUIs and generate a .ui
file. You can then run pyuic4
to turn this XML description file into a python template. From there you can subclass the object and add your non-gui python code - this has the advantage that you can tweak the gui and rerun pyuic4
without overwriting your hand-written additions.
Of course PyQt isn't the only option available for making graphical things with python. Another option is the Gtk libraries (used most famously by the Gnome project) and their python bindings pygtk. A simple python example for launching a gui is shown here:
import pygtk pygtk.require('2.0') import gtk class Base: def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.button = gtk.Button("Hello from Python") self.window.add(self.button) self.button.show() self.window.show() def main(self): gtk.main() if __name__ == "__main__": base = Base() base.main()
And again, the result looks more or less identical to the Qt example apart from minor font differences.
Of course you can write any python programs you like with a simple text editor, and many of them (such as gedit) provide coloured highlighting according to the language. Then simply save the file, Alt-Tab to your console (or F12 to your dropdown Tilda console) and run your python program from there. But as with programming in any language, a dedicated graphical development environment can provide many useful tips such as outlines, cross-referencing, running with a single click and other clever customisations.
There are dedicated python-only IDEs, such as Eric or IDLE, but a good alternative if you're already used to eclipse is the "pydev" plugin. After a simple download (from inside eclipse using Help->Install New Software), and a little configuring to point it to your selected python executable, you can quickly create a project, use the pydev perspective and take advantage of the neat features. That's also a nice way to get svn integration, using the subclipse plugin (see version control for more on subversion).
See pydev.org for more details on pydev, or see wikipedia for other IDE suggestions.
The first port of call should be the excellent python.org which has a wealth of information including a raft of documentation and a lengthy tutorial. For an extremely thorough walkthrough of basic programming with focus on Python, see Alan Gauld's tutorial which also makes comparisons to Javascript... and also see Wikipedia's Python page.
For a detailed guide to using Qt with Python, see GUI Programming with Python, and for general Qt information see trolltech.com. For some simple examples of using Pyqt and QtDesigner, see Beaver's PyQt page.