58
Introduction to Python

Python Intro

Embed Size (px)

DESCRIPTION

An introduction to python given at the Computer Science departmental seminar at Otago University, NZ on the 27th March 2009.

Citation preview

Page 1: Python Intro

Introductionto

Python

Page 2: Python Intro

    2

Aim of this talk

Show you that Python is not a noddy language

Get you interested in learning Python

Page 3: Python Intro

    3

Before we start

Who am I?

Page 4: Python Intro

    4

Tim Penhey

Otago University Comp Sci 1991­1994 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

Page 5: Python Intro

    5

Page 6: Python Intro

    6

Quick Question

What languages are you tought as an undergraduate now?

When I was here we did: Pascal; Modula­2; LISP; Prolog; Assembly; C; Haskell; ML; Ada; and Objective C (kinda)

Page 7: Python Intro

    7

Python

Not named after this...

Page 8: Python Intro

    8

Page 9: Python Intro

    9

Python

... but this ...

Page 10: Python Intro

    10

Page 11: Python Intro

    11

Python

... by this man ...

Page 12: Python Intro

    12

Page 13: Python Intro

    13

Guido van Rossum

Python's BDFL http://www.python.org/~guido/ Blog http://neopythonic.blogspot.com/ Now works for Google

Page 14: Python Intro

    14

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

Page 15: Python Intro

    15

Python has...

very clear, readable syntax strong introspection capabilities intuitive object orientation natural expression of procedural code full modularity, supporting hierarchical 

packages exception­based error handling

Page 16: Python Intro

    16

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

Page 17: Python Intro

    17

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)

Page 18: Python Intro

    18

Python runs everywhere

All major operating systems Windows Linux/Unix Mac

And some lesser ones OS/2 Amiga Nokia Series 60 cell phones

Page 19: Python Intro

    19

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

Page 20: Python Intro

    20

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 

Page 21: Python Intro

    21

The Zen of Python

Beautiful is better than ugly.

Page 22: Python Intro

    22

The Zen of Python

Explicit is better than implicit.

Page 23: Python Intro

    23

The Zen of Python

Simple is better than complex.

Page 24: Python Intro

    24

The Zen of Python

Complex is better than complicated.

Page 25: Python Intro

    25

The Zen of Python

Flat is better than nested.

Page 26: Python Intro

    26

The Zen of Python

Sparse is better than dense.

Page 27: Python Intro

    27

The Zen of Python

Readability counts.

Page 28: Python Intro

    28

The Zen of Python

Special cases aren't special enough to break the rules.

Page 29: Python Intro

    29

The Zen of Python

Although practicality beats purity.

Page 30: Python Intro

    30

The Zen of Python

Errors should never pass silently.

Page 31: Python Intro

    31

The Zen of Python

Unless explicitly silenced.

Page 32: Python Intro

    32

The Zen of Python

In the face of ambiguity, refuse the temptation to guess.

Page 33: Python Intro

    33

The Zen of Python

There should be one — and preferably only one — obvious 

way to do it.

Page 34: Python Intro

    34

The Zen of Python

Although that way may not be obvious at first unless you're 

Dutch.

Page 35: Python Intro

    35

The Zen of Python

Now is better than never.

Page 36: Python Intro

    36

The Zen of Python

Although never is often better than right now.

Page 37: Python Intro

    37

The Zen of Python

If the implementation is hard to explain, it's a bad idea.

Page 38: Python Intro

    38

The Zen of Python

If the implementation is easy to explain, it may be a good idea.

Page 39: Python Intro

    39

The Zen of Python

Namespaces are one honking great idea — let's do more of 

those!

Page 40: Python Intro

    40

Hello World

Python 2.6 print “Hello World”

Pyton 3.0 print(“Hello World”)

Page 41: Python Intro

    41

My Python Favourites #2

The interactive interpreter

Page 42: Python Intro

    42

Datatypes

All the usual suspects Strings (Unicode) int bool float (only one real type) complex files

Page 43: Python Intro

    43

Unusual Suspects

long — automatic promotion from int if needed

>>> x = 1024

>>> x ** 50

3273390607896141870013189696827599152216642046043064789483291368096133796404674554883270092325904157150886684127560071009217256545885393053328527589376L

Page 44: Python Intro

    44

Built­in 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”])

Page 45: Python Intro

    45

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

Page 46: Python Intro

    46

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)

Page 47: Python Intro

    47

Classes

class MyClass:

  """This is a docstring."""

  name = "Eric"

  def say(self):

    return "My name is %s" % self.name

instance = MyClass()

print instance.say()

Page 48: Python Intro

    48

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

Page 49: Python Intro

    49

Exceptions

Also used for flow control – StopIteration Exceptions are classes, and custom exceptions 

are easy to write to store extra state informationraise SomeException(params)

try:

    # Do stuff

except Exception, e:

    # Do something else

finally:

    # Occurs after try and except block

Page 50: Python Intro

    50

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

Page 51: Python Intro

    51

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

Page 52: Python Intro

    52

Metaprogramming

Descriptors

Decorators

Meta­classes

Page 53: Python Intro

    53

My Python Favourites #3

The Python debugger

import pdb;

pdb.set_trace()

Page 54: Python Intro

    54

Other Domains

Asynchronous Network Programming Twisted framework ­ http://twistedmatrix.com

Scientific and Numeric Bioinformatics ­ biopython Linear algebra, signal processing – SciPy Fast compact multidimensional arrays – NumPy

Desktop GUIs wxWidgets, GTK+, Qt

Page 55: Python Intro

    55

What is Python bad at?

Anything that requires a lot of mathmatical computations

Anything that wants to use threads across cores or CPUs

Real­time systems

Page 56: Python Intro

    56

Work arounds

Write extension libraries in C or C++

Use multiple processes instead of multiple threads

Use a different language

Page 57: Python Intro

    57

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 7­8 November 2009 (that's this year!)

Page 58: Python Intro

    58

Questions?