A Brief Introduction to Python

"One, two, five!" -- King Arthur, Monty Python

Author: Stéfan van der Walt
Date: 14/02/2007

What is Python?

From the Python website:

Python is a powerful, yet easy to learn programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python's elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for both scripting and rapid application development in many areas and on most platforms.

To recap without the geekspeak:

but realise that there is no magic bullet.

To be a bit more specific...

it's fun!

The Zen of Python (by Tim Peters)

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> import this

But my code must fly...

...and Python is way too slow for me

Modified from Greg Wilson's Software Carpentry course:

human_vs_machine_time_mod.png

What about MATLAB?

  • Reasons not to are philosophical and practical
  • Let's stick to practical for now

Plug for Software Carpentry

To quote Greg Wilson's Scipy06 slides:

  • Best time to teach scientists something new is in grad school
    • They're in for the long haul, so investment makes sense
    • They welcome excuses to procrastinate
    • And everyone welcomes a Plan B

Software Carpentry course -- learn to develop, rather than to grind out code

  • Version control
  • Unit testing
  • and more...

Time to get our hands dirty...

Let's print all the elements of a sequence...

C++

#include <iostream>

#define FIB_LEN 7

int main()
{
   
int fibo[FIB_LEN] = {1,1,2,3,5,8,13}; // or std::vector

   
for (int i = 0; i < FIB_LEN; i++) {
       
std::cout << fibo[i] << std::endl;
   
}
}

vs. Python

fibo = [1,1,2,3,5,8,13]
for nr in fibo: print nr

Now someone tells you to change the length of the list, the element types, the numbers of elements etc.

Python's for loop can use any iterable -- including generators:

def fib(n):
    
"""Calculate the n-th element of the Fibonacci series"""
    
if n < 2:
        
return 1
    
else:
        
return fib(n-2) + fib(n-1)
def fib(n):
    
"""Generate the first n members of the Fibonacci series."""
    
prev, cur, i = 0,1,0
    
while i < n:
        
cur, prev = prev + cur, cur
        
i += 1 # or i = i + 1
        
yield prev

The building blocks

The building blocks (cont'd)

def greet(name, word='Hello'):
    
print word + ', ' + name + '!'
def greet(name, word='Hello'):
    
print '%s, %s!' % (word, name)
class Apple:
    
colour = 'red'
    
def __init__(self, colour='red'):
        
self.colour = colour
    
def eat(self):
        
print 'I am munching a delicious, %s apple.' % self.colour

Find structure of classes while refactoring code.

The building blocks (cont'd)

Try this at home

Further Resources