Python
From DmWiki
Python (http://python.org/) is a popular object-oriented programming language. Some would say it's only a scripting language because it's interpreted, but that's neglecting the completeness and the beauty of the language (modules, classes, exceptions, ...) and also the fact that it really isn't interpreted in run-time. Like Java, Python modules are compiled into bytecode files, which is then executed by a virtual machine. Python is often compared to Perl, Ruby, and Tcl. Also, Python uses automatic garbage collection and supports a measure of object-oriented programming.
One of the curiosities of the language is the strict use of identation to indicate code blocks (in contrary to for example C++ that uses curly brackets {}). One other feature to note is that everything in python is an object. An object with methods and properties (btw, in the C API everything is a pointer to a PyObject).
i = 0
while i < 5:
print i
i += 1
This will print
0 1 2 3 4
You can also write this by iterating over a range of 0 to 5:
for i in range(5):
print i
One of the cooler features of Python is list comprehensions. Basically, if you want to transform one sequence in another, you use a list comprehension. For example, say, we want a list of the first five squared numbers. You'd do something like this:
numbers = range(5) print numbers squared = [x**2 for x in numbers] print squared
It would print
[0, 1, 2, 3, 4] [0, 1, 4, 9, 16]
Another cool feature is that you can directly iterate over the lines in a textfile. Say, we have a file foo.txt which contain a matrix:
1 2 3 4 5 6 7 8 9
Then we read this in one line of code as following:
matrix = [[float(x) for x in line.split()] for line in file("foo.txt")]
print "matrix:", matrix
print "matrix[1][2]:", matrix[1][2]
It uses a double list comprehension. The outer one reads the file line by line, and the inner one splits each line and convert the numbers from strings to floats. The result is a list of three lists:
matrix: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] matrix[1][2]: 6
Resources
- python.org
- IronPython (http://www.ironpython.com/) A .NET python implimentation
- PyGame (http://www.pygame.org/) A multimedia extension commonly used in game design.
- PyPy (http://codespeak.net/pypy/dist/pypy/doc/news.html) A Python to C or LLVM code converter
