Introduction to Python
Aim of this talk
Show you that Python is not a noddy language
Get you interested in learning Python
2
Before we start
Who am I?
3
Tim Penhey
Otago University Comp Sci 19911994
Intermittent contractor for 12 years
Started working for Canonical over 2 years ago
First started with Python 8 years ago after reading “The Cathedral & the Bazaar” Python has been my primary development language for around three years now
4
5
Quick Question
What languages are you tought as an undergraduate now? When I was here we did: Pascal; Modula2; LISP; Prolog; Assembly; C; Haskell; ML; Ada; and Objective C (kinda)
6
Python
Not named after this...
7
8
Python
... but this ...
9
10
Python
... by this man ...
11
12
Guido van Rossum
Python's BDFL
http://www.python.org/~guido/
Blog http://neopythonic.blogspot.com/
Now works for Google
13
Python History
Implementation started Dec 1989
Feb 1991 released to alt.sources
Jan 1994 1.0.0 released
Oct 2000 2.0 released
Oct 2008 2.6 released
Dec 2008 3.0 released
2.7 and 3.1 in development
14
Python has...
very clear, readable syntax
strong introspection capabilities
intuitive object orientation
natural expression of procedural code
full modularity, supporting hierarchical packages exceptionbased error handling
15
Python has...
very high level dynamic data types an extensive standard libraries and third party modules for virtually every task extensions and modules easily written in C, C++ (or Java for Jython, or .NET languages for IronPython) the ability to be embedded within applications as a scripting interface
16
Python plays well with others
Python can integrate with COM, .NET, and CORBA objects Jython is Python for the JVM and can interact fully with Java classes IronPython is Python for .NET Well supported in the Internet Communication Engine (ICE http://zeroc.com)
17
Python runs everywhere
All major operating systems
Windows
Linux/Unix
Mac
And some lesser ones
OS/2
Amiga
Nokia Series 60 cell phones
18
Python is Open
Implemented under an open source license
Freely usable and distributable, even for commercial use.
Python Enhancement Proposals – PEP
propose new features
collecting community input
documenting decisions
19
My Python Favourites #1
The Zen of Python
PEP 20 Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down.
aphorism – A tersely phrased statement of a truth or opinion
20
The Zen of Python
Beautiful is better than ugly.
21
The Zen of Python
Explicit is better than implicit.
22
The Zen of Python
Simple is better than complex.
23
The Zen of Python
Complex is better than complicated.
24
The Zen of Python
Flat is better than nested.
25
The Zen of Python
Sparse is better than dense.
26
The Zen of Python
Readability counts.
27
The Zen of Python
Special cases aren't special enough to break the rules.
28
The Zen of Python
Although practicality beats purity.
29
The Zen of Python
Errors should never pass silently.
30
The Zen of Python
Unless explicitly silenced.
31
The Zen of Python
In the face of ambiguity, refuse the temptation to guess.
32
The Zen of Python
There should be one — and preferably only one — obvious way to do it.
33
The Zen of Python
Although that way may not be obvious at first unless you're Dutch.
34
The Zen of Python
Now is better than never.
35
The Zen of Python
Although never is often better than right now.
36
The Zen of Python
If the implementation is hard to explain, it's a bad idea.
37
The Zen of Python
If the implementation is easy to explain, it may be a good idea.
38
The Zen of Python
Namespaces are one honking great idea — let's do more of those!
39
Hello World
Python 2.6
Pyton 3.0
print “Hello World”
print(“Hello World”)
40
My Python Favourites #2
The interactive interpreter
41
Datatypes
All the usual suspects
Strings (Unicode)
int
bool
float (only one real type)
complex
files
42
Unusual Suspects
long — automatic promotion from int if needed
>>> x = 1024 >>> x ** 50 327339060789614187001318969682759915221 664204604306478948329136809613379640467 455488327009232590415715088668412756007 1009217256545885393053328527589376L
43
Builtin datastructures
Tuples – Fixed Length
(1, 2, 3, “Hello”, False)
Lists
[1, 2, 4, “Hello”, False]
Dictionaries
{42: “The answer”, “key”: “value”}
Sets
set([“list”, “of”, “values”])
44
Functions
Python uses whitespace to determine blocks of code (please don't use tabs)
def greet(person): if person == “Tim”: print “Hello Master” else: print “Hello %s” % person
45
Parameter Passing
Order is important unless using the name
def foo(name, age, address)
foo('Tim', address='Home', age=36)
Default arguments are supported
def greet(name='World')
Variable length args acceptable as a list or dict
def foo(*args, **kwargs)
46
Classes class MyClass: """This is a docstring.""" name = "Eric" def say(self): return "My name is %s" % self.name instance = MyClass() print instance.say()
47
Modules
Any python file is considered a module
Modules are loaded from the PYTHONPATH
Nested modules are supported by using directories.
~/src/lazr/enum/__init__.py
If PYTHONPATH includes ~/src
import lazr.enum
48
Exceptions
Also used for flow control – StopIteration Exceptions are classes, and custom exceptions are easy to write to store extra state information raise SomeException(params) try: # Do stuff except Exception, e: # Do something else finally:
49
# Occurs after try and except block
Duck Typing If it walks like a duck and quacks like a duck, I would call it a duck – James Whitcomb Riley
There is no function or method overriding
Methods can be checked using getattr
Consider zope.interface
50
Batteries Included
The Python standard library is very extensive
regular expressions, codecs
date and time, collections, theads and mutexs
OS and shell level functions (mv, rm, ls)
Support for SQLite and Berkley databases
zlib, gzip, bz2, tarfile, csv, xml, md5, sha
logging, subprocess, email, json
httplib, imaplib, nntplib, smtplib
and much, much more
51
Metaprogramming
Descriptors
Decorators
Metaclasses
52
My Python Favourites #3
The Python debugger
import pdb; pdb.set_trace()
53
Other Domains
Asynchronous Network Programming
Scientific and Numeric
Bioinformatics biopython
Linear algebra, signal processing – SciPy
Fast compact multidimensional arrays – NumPy
Desktop GUIs
Twisted framework http://twistedmatrix.com
wxWidgets, GTK+, Qt
54
What is Python bad at?
Anything that requires a lot of mathmatical computations Anything that wants to use threads across cores or CPUs Realtime systems
55
Work arounds
Write extension libraries in C or C++ Use multiple processes instead of multiple threads Use a different language
56
NZ Python Users Group
http://nzpug.org
Regional meetings, DunPUG
Mailing list using google groups
Planning KiwiPyCon
2 day event over a weekend in Christchurch
78 November 2009 (that's this year!)
57
Questions?
58