Python intro by www.ixi-software.net 

This is a fast an informal introduction to python. You should go over the python tutorial that can be found at www.python.org as that is a proper introduction to thePython basics. The aim of this one is to give a very fast overview to it so that you get a basic understanding of its scope, syntax and particularities.

  ---------------------------------------------------------------
 Copyright (c) 2006, ixi software.
 This work is licensed under a Creative Commons 
Attribution-NonCommercial-ShareAlike 2.0 England & Wales License.
  http://creativecommons.org/licenses/by-nc-sa/2.0/uk/
  ---------------------------------------------------------------

Installing Python:

- GNU/Linux:
It comes with the system in most (all?) distributions, under Debian just need to apt-get or use Sypnaptics to install/upgrade Python and any package or library you might need. There are millions of editor to choose. I use the one that comes with python, IDLE.

- Windows:
Just download and install, from www.python.org. It contains a python editor (IDLE) we can use to code, but there are many others you might want to use
To do graphics we will also need PyOpenGL and/or Pygame (SDL).

- OSX :
Python comes installed with OSX by default.
*update: i am not sure how Python works on OSX 10.5 so this explanation below is only valid in principle for OSX 10.4*
However, I *strongly* recommend to install python 2.4 version, the built in one is 2.3 and it is old and more difficult to deal with.
So, on mac we need:
Download and install Python 2.4 and packages we want to use from this page
A nice editor : ScrIDE is another one dedicated to Python. Smultron is also nice but less Python oriented. IDLE can be used, but you might find it a bit weird to use because key bindings are not Apple-friendly
And to play with graphics:
PyOpenGL - from mac python 2.4 packages
Pygame - from mac python 2.4 packages
(make sure you install the one for your OSX version and main Python version installed!, in this case 2.4)
To be sure all went right try opening a terminal, type "python" and hit enter. You should get python2.4 and NOT 2.3. Now type "import pygame" and hit enter, do the same with "import OpenGL". If you get no errors, all is right. These are some URLs that can help understanding better Python on mac :
intro to python on mac
http://bill.janssen.org/mac/new-macpython-page.html

There are other systems where Python runs but we wont cover them (solaris, Nokia, java, .NET, and many others ...)

anything else??
- Mirra
This is a nice graphic framework we use to do 2D graphical interfaces (based on OpenGL and wxpython) and an OSC implementation to send OpenSoundControl messages.

OK, we should be ready to start ...

 

 

What is python?

http://en.wikipedia.org/wiki/Python_programming_language
Python is a scripting language like Ruby, Perl or javascript (lingo and actionscript could be considered scripting languages too).
Allows for procedural and Object Oriented Programming
Tries to be elegant and easy/clean to code and understand.
Python itself it is small but the python community provides with loads of external libraries to do extra stuff, like for example programming a GUI or graphics, instead of having everything incorporated into language (unlike Java or Perl), .
It is optimised for programmer performance and not machine performance -> faster development period, easy to change project direction and to reuse the code.
Jython - is Python implemented on Java (Normal Python is actually C-Python, implemented in C) This means that Jython can access all the java built in libraries, (but not the ones developed for CPython unless they are translated, many of them to be done). Jython still is growing up, but it is getting interesting.
Like other scripting languages it is interpreted by the Python interpreter on the fly.
It is Crossplatform (windows, OS9/OSX, GNU/linux, solaris, Nokia, java, .NET......)
It is Free Source -> it grows veery faaast, it has a friendly comunity, mailing lists, loads of examples online. everything free and open.
It is a general purpose language (like C or Java, unlike PHP or Actionscript focused on web scripting)
It is a good language to learn programming because of its clear and flexible syntax.
It is used in any different professional fields like in the game industry, software prototyping, as a 'glue' language between libraries, as scripting language for different packages (Blender, Zope, Maya, PureData ...).

Check this 70min long interview with Guido Van Rossum , python's creator, if you are interested on an *in depth* overview of the why, when and hows around Python.



How is Python ?

Indentation : Beware of tabulations and spaces! Indentation separates the code blocks, like this:

def afunction:
       somecode
       morecode
       if something:
              blahblah
              somemoreblahblah

Warning about indentation:
Different systems and editors use different ways to deal with tabs. The Python standard is that tabs should be converted to spaces. If you open youir files in another editor or system and the indentation is totally different then you have to check this in your editor. Remember that this is quite important if you are giving your files to somebody else. If you want to read more about this here it goes this link http://www.python.org/doc/2.0.1/ref/indentation.html

Check the difference between Java (or C) and Python in this example
C / Java code :

boolean x;
x = True;
if (x) {
dothis();
}

Python code :

x=True
if x:
   dothis()

So there are no semicolons ; at the end of the lines and everything within a block should be have same indentation, no need to use { }. Therefore:

if x:
   someX
   someotherX
if y:
   somethingelseY
   if somemoreY :
      somethingelsemoreY

etc...

Python is simlar to Perl in concept but it is aparently its easier to learn as it is said to be far more clear to write and read (actually, there is a very good joke about this, check the cartoon below) . Here it goes some crazy obscure Perl script by Yaxu (Slab):
#!/usr/bin/perl
open F,'>/dev/dsp';$m='ub . . .quicksort techno. . . sl';
while(){@d=sort{push@o,$a,$b;$a<=>$b}map{512-rand(1023)}0..
1023;for(0..3){map{print F pack'C',$_;$m=~s{^(.)(.*)}{$2$1}
;printf"\e[%d;%dH$1",13.5-25*($_/1024),++$f%80+1}@o}}# yaxu

Of course not all Perl looks like this, I choose this one because it is specially obscure ... Python would have forced him to do the same in a more 'clean' way and it would make it easier for us to understand what Yaxu was trying to do there. Therefore Python would, at least in theory, help creating reusable code.


http://comic.escomposlinux.org

Python is claimed to be one of the easiest language to learn proper programming. It is also similar to Ruby but this is totally OOP and it is less spread. (BTW. Ruby is a very interesting language as well, keep an eye on it).

Python is good to do things that requiere fast developing and testing. Prototyping, scientific research tasks etc.. Or tasks that requiere quick frequent changes during development process. It is far easier to update and maintain than C or Java.

Launching Python interactive mode :
windows : in python menu
osx + linux : type Python in the terminal


Syntax:
print "hello world"
try some basic maths (+, /, *, etc ...)
# for one line comments
"""" triple quotations for longer descriptions
""""
no need to declare data types or variables (only globals when changing its value. I explain this later).
x = 5
x = "hey"
x = Object() #instanciating an object


Non Interactive Python :
Python files are .py 
--> running .py files
win - just doubleclick
linux - On the terminal type : python /whatever_path/filename.py
osx - drop them on to the python launcher that comes with macpython or use terminal like in linux

Printing some stuff
print 5+3/2.1
print  4,5,2, 'hey'
print 'hi %s %i  pints  % ('peter', 4) #-- will print  the string 'hi peter 4 pints'

try this:
example1


Basics of programming in Python:

Tabs and spaces! are crucial in python
--> importing libraries
import random
r = random.Random()
print r.random()
print r.randint(10, 20)

example2 | example3


Control structures / programming blocks / Conditionals
q = 4
h = 5

if q<h:
   print "q is smaller than h"
elif q==4:
   print "q is equal to h"
else:
   print "q is bigger than h"

example4

Operators:
and, or, not
==, !=, >, <
Loops :
while b < 10:
       print b
       b += 1 # there is no ++ symbol unlike Java or C
nums = [1, 2, 4] # this is an array or list
months = ["june", "july", "august"] # another array containing strings
for x in nums : print x # some loops
for y in months: print y
for n in range(19): print n

example5

Tuples - (3, 2) CANNOT change, they are constant, for example they are useful in functions to return several values at the same time, etc... like this:
def afunc() :
        return (x, y )
x = (2, 3, 4) is the same as x = 1, 2, 3
so in a function you return a tuple like this--> return size, height, width
I guess because it is inmutable it is cheaper than returning an array, which in python (again unlike Java or C) can change its size on the fly.
Diccionaries -- like property list in lingo (Macromedia Director)
dic = {"name": "Peter", "surname":"Pan", "age": 38}
print dic["name"]
They are also called sometimes associative arrays

example6

Functions:
Arguments, *args, **kwargs, <--- different ways to define arguments in functions
def add(a, b):
      sum = a+b
      return sum

Default arguments. Sometimes you want to give a default value in case none is passed
def add(a=5, b=10):
      sum = a+b
      return sum

example7


Errors and Exceptions:
They are a nice way to avoid script errors, if something goes wrong you can always find a way to gently stop the program or try something else. Good to use for example when you are importing libraries that might not be installed in the user machine, stuff that it does not depend on the code you are writing itself.

example8.1

 

Basic program structure

example8 | example9 |example10

 

Global variables:
Any variable created outside any definition or class is a global (within that module!). Top avoid errors the best is to declare them in any function you use them. (You will actually find that when reasigning its value they MUST be declared within the function that change its value but if you are just using them there is no need to declare.)

exampla11 | example12

 

Classes:
by convention first letter of name is Capital. And also by convention self is used to refer to the actual instance of the class, a bit like this in Actionscript, Java or C. You could actually use carrot instead of self, but lets follow the conventions ...
class Counter:
   def __init__(self): # constructor method
       self.count = 0
   def add(self, delta):
       self.count += delta
   def getCount(self):
       return self.count

example13 | example14

 

Python properties-
In new versions of Python the OOP has been enhadced and symplified in some ways. You will find people still coding 'old style' while some others will do new style. This is not so important for you at the moment, but lets have a look at a cool way to use properties the with the new style of Python.
In java there are special methods called setters and getters, those are to access and modify instances properties (atributes) indirectly.  Python has a nice way (similar to Ruby) to avoid having to declare all those getters and setters.  This is by using the property() built in function. I wont go into this further, just wat to mention it so that if you find it somewhere it rings some bells and you dont get confused. If you are interested on this check the python documentation. You can also look into the source code of Mirra in the graphics.py module, check the Base class.

Inheritance:
Classes that inherit from a superclass had to declare this one on brackets. And in general you have to initialise its superclass __init__() constructor as well. They inherit all methods and properties from their superclasses.
class CounterWithMax(Counter):
     def __init__(self, max):
          Counter.__init__(self) # here we make sure that the superclass constructor method is initialised as well.
          self.max = max
     def reset(self):
         if self.count >= self.max:
         self.count = 0
In this case CounterWithMax has inherited the property count and methods add() and getCount() and it has extended the __init__ by adding the new property max.
It has also defined a new method called reset()

example15 | example16

The above would be achived as well without using inherintnce by doing this:
class CounterWithMaxButNoInheritance:
   def __init__(self, max):
      self.count = 0
      self.max = max
  def add(self, delta):
      self.count += delta
  def getCount(self):
      return self.count
  def reset(self):
        if self.count >= self.max:
                self.count = 0
Exactly the same, but you will find very soon the benefits and power of using inheritance

 

Multiple inheritance:
This is not possible in Java or C++, there you would use Interfaces to achive similar results. Lets define a new class and then create one that inherit from Counter and YieldOnEven on example 17
class YieldOnEven():
         def __init__(self):
              pass
        def checkEvens(self, num):
              if num % 2 == 0: # if reminder of num/2 is 0 then is an even number
                       print "IT WAS AN EVEN NUMBER!"

example17

 

Modules, creating and importing modules:

example18

 

Packages:
they are similar to jars in Java. Check the online tutorial for detailed description.

More on importing:
There are few ways to import from modules and packages, here there are some ...
import module
# imports eveything in mirra. Access by module.Class or module.function
import module.submodule
# imports eveything within module.submodule. access by module.submodule.function() or module.submodule.function()
from module import submodule
# imports utilities module from mirra BUT access is more direct -- submodule.function()
#you could actually do this
from module import submodule.function
# and you would access the funcion directly -- function()
from module.submodule import *
# imports all within module.submodule and it can be accessed directly -- Class() or function()
import module.submodule as blah
# Imports that module and it can be accessed with that new name -- blah.function()

Be careful as some of the methods to import can be misleading. For example 'from module import *' allows to access al methods and classes within a module or package directly without referring to the module or package where they are defined. This can cause confussions when we dont know where some function or class we are using is actually defined. Use the simplest (import module.submodule) for start so that there are no problems.

Extensions in C/C++:
Sometimes Python is too slow for some fast calculations. Lets say you are calculating collisions between hundreds of objects every frame. For those cases C and C++ extensions can be wrote, and it is actually not that difficult. ;) Check the python documentation for how to do this, there is also an example we did here


---------------------------------------

Python and OSC :
Simple way to send and receive OSC in Python. Download from SimpleOSC

A case study :
The fact that there is no data type in Python allows to do code far shorter that in C/C++/Java. Consider this :

def afunc(a,b):
        return a+b

This function would work fine in all the following cases
a = afunc(5,4) 
# returns 9
a = afunc(5.1, 4.4) 
# returns 9.5
a = afunc("he", "llo")
# returns "hello"

In C/C++/Java you will need two different functions one to add integers, another to add float point values, and another to concatenate strings. Furthermore in some more complex scenarios the use of for example default arguments in the functions this can help reducing the code quite massively compared. This is just to illustrate the porpouse of Python. To be clean and as minimal as possible helping reducing production time.

Each language is good for something different. You just need to find the one that suits you and your needs better.

 -------------------------------------

Documenting Python:
There is a very detailed convention about how to document python. Check the tutorial for details. Its a good idea to stick it as much as possible.

Coding Guidelines:
http://www.python.org/doc/peps/pep-0008/

Libraries:
We will comment here some, but there are hundreds of libraries. They are usually wraps around C libraries, this means they run quite fast.
- GUI building libraries.
tkinter, wxWidgets (wxpython), ...
- Libraries to do graphics :
pyOpenGL, Pygame (SDL), PyCairo (Vector graphics), Python ImageLibrary. (also known as PIL), PyGLet ....
- Mirra is 2D graphics framework by ixi (a bit like Processing). We use it to create our applications. Uses python+OpenGL
An OpenGL+Pygame 2D Tutorial can be found here
some examples of different graphics libraries:
opengl | pygame(SDL) | wxPython + pyOpenGL
- OpenSoundControl library
SimpleOSC : ixi wrap for Daniel Holtz implementation
www.ixi-software.net/content/body_backyard_code.html
www.ixi-software.net/content/body_backyard_code.html
- SC library
Controlling Supercollider SCSynth from Python

Hundreds of other libraries can be found and downloaded at the Python Cheese Shop


Python within PureData (and MAX/MSP):
Python can be used to script pure data via py/pyext external.
http://grrrr.org/ext/py
Python modules can be imported into PD and its functions can be called and can return values to PD. With pyext classes can be used as well. This is a way of creating python externals for PD in a way. This is really powerful as otherwise to create externals we need to use mainly C++.
Here we have an example of a PD patch and a python module imported into it.

Gamepads and joysticks - HID devices in Python:
Hid devices can be accessed via many libraries such as Pygame (SDL) , PyOpenGL (with GLUT) or wxPython. Pygame is probably the easiest way to use it.
Here it is a very simple example. Note that Mirra includes HID support.

Hands-on Python:
Use the Mirra to test your python skills. Try to do the circle exercise

 

Thats all folks! we hope you enjoyed Python, a very nice and interesting language which can serve many purposes.