63
Introduction to Python Programming Giles Hall <[email protected]> Jan 10, 2006 SIPB IAP 2006

Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Embed Size (px)

Citation preview

Page 1: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Introduction to Python Programming

Giles Hall <[email protected]>

Jan 10, 2006

SIPB IAP 2006

Page 2: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Python

• Python is a programming language that is powerful and free.

• Very-high-level language.

• Appropriate for prototyping, scripting, web applications, client/server, XML processing, and much more.

Page 3: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Python’s Easy

• Easy to Learn– The documentation is an incredible,

comprehensive resource that’s easy to read.

• Easy to Understand– Python code looks a lot like “pseudocode”.

• Easy to Code– Translating thought to code is extremely

straight-forward.

Page 4: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

What’s So Good About It?

• Free (http://www.python.org/)

• Open source

• Portable

• Modern

• Well documented

• Robust

Page 5: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

What’s so Good About it?

• Interpreted language – no compilation or linking is necessary.

• Interactive interpreter.

• Flexible, powerful, generic high-level data types that make it easy to accomplish complex operations in a single statement.

Page 6: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

What’s so Good About it?

• Rapid Application Development– It’s a scripting language

• Large base of software– Comprehensive standard library– Contributed packages from the internet

• Active, enthusiastic Community

Page 7: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Enterprise Python

• Many companies around the world use python in their software products:– Noteworthy users include Google, Yahoo,

Industrial Light & Magic, National Weather Service, NASA, Red Hat, MCI Worldcom.

Page 8: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Python On The Web

http://www.python.org

- Python Runtime

- Documentation

- Anything else, very helpful!

Page 9: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

How To Install?

• Download– Follow the links on http://www.python.org/

• Run Installer– Windows: MSI Installer – Mac OSX: dimg Installer– Linux: RedHat .rpm / Debian .deb

Page 10: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

How To Learn?

• Python has excellent documentation.– The Tutorial is a wonderful trainer (it’s how I

learned it years ago!):• http://docs.python.org/tut/tut.html

– The Library Reference documents all of Python’s standard extensions like regex, os or the HTTP library:

• http://docs.python.org/lib/lib.html

Page 11: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Interpreter

• Ask Python a Question?

• Get Back an Answer!Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32Type "copyright", "credits" or "license()" for more information.

>>> 11>>> 22>>> 1 + 23>>> "hi"'hi'

Page 12: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Scope

• Python uses indentation to define a scope

>>> if (variable == True):........print "It's True!"else:........print "It's not True!“It's True!

Page 13: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Classic Python

• It's easy to compute the Fibonacci series:

- http://docs.python.org/tut/node5.html

>>> a, b = 0, 1>>> while b < 10:........print b........a, b = b, a+b

112358

Page 14: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

True, False

• True and False are defined for you.

>>> TrueTrue>>> FalseFalse>>> True == FalseFalse>>> 1 == 1True

Page 15: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

More on True and False

• True and False are variables representing 1 and 0, but are not integers themselves:

>>> TrueTrue>>> 11>>> 1 == TrueTrue>>> 2 == TrueFalse>>> 0 == FalseTrue

Page 16: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Boolean Operators

• Boolean and>>> True and False

False

>>> True and True

True

• Boolean or>>> 1 or 0

1

• Boolean operator not>>> not True

False

Page 17: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Calculator

• Python is a Useful Calculator

>>> 365 * 24 * 60 * 6031536000>>> 100 / 254>>> 3.14 * 7 ** 2153.86000000000001>>> 3 % 21>>> 3 % 30

Page 18: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Integer vs. Float

• Python differentiates floats from integers:

• A decimal zero will coerce python to preserve the decimal in the result:

>>> 3 / 21

>>> 3 / 2.01.5

Page 19: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Calling Functions

• Not surprising, python's function calls look a lot like other languages. The function name is appended by a pair of parenthesis that encapsulate the function arguments. Here is an example call to python's absolute value function:

>>> abs(-1)1

Page 20: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Builtin Functions

• Out of the box, the python environment provides a standard set of functions:

>>> max(10,20)20>>> len("size matters")12>>> hex(31337)'0x7a69'>>> ord('a')97>>> chr(100)'d'

Page 21: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Variables

• Python provides a global namespace to associate data with variables.

>>> a = 1>>> b = 2>>> a + b3>>> x = “Good">>> y = “Bad">>> x + y‘GoodBad'

Page 22: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Namespace

• You can explore the global namespace with the builtin commands dir() and globals()

>>> a = 1>>> b = 2>>> dir()['__builtins__', '__doc__', '__name__', 'a', 'b']>>> globals(){'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'b': 2, '__doc__': None, 'a': 1}

Page 23: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Memory Management

• Python achieves memory management through reference counts.

• A single variable represents a single reference to a piece of data. Each separate reference increments the data's reference count.

Page 24: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Memory Management

• When a reference count decrements to zero, python will harvest the memory used by the referenced data towards other memory allocations.

• The python keyword del does not delete data, it simply decrements its reference count.

Page 25: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Example use of del>>> x = 1>>> x1>>> del x>>> xTraceback (most recent call last): File "<stdin>", line 1, in ?NameError: name 'x' is not defined

Page 26: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Types

• Python associates type information with real-data:

• Python provides a slew of builtin types, including a variety of data structures...

>>> x = 1>>> type(x)<type 'int'>>>> type(1.1)<type 'float'>>>> type(True)<type 'bool'>

Page 27: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

What is a Data Structure?

"[Data structures are] a way of storing data in a computer so that it can be used efficiently ... A well-designed data structure allows a variety of critical operations to be performed, using as little resources, both execution time and memory space, as possible. "

- http://en.wikipedia.org/wiki/Data_structure

Page 28: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Data Structures

• In order for a program to function, in needs to be able to access data.

• Data can not be strewn about, they must be organized.

• Data structures provide programs a means to contain and organize data.

• Python provides many sophisticated, generic data structures including strings, lists, tuples, sets, and dictionaries.

Page 29: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Strings

• A “string” in computer science is a sequence of simple objects or characters. This sentence can be represented as a string.

• Think: a string of letters.>>> "Don't forget to tie up loose ends.""Don't forget to tie up loose ends.">>> type("What am I?")<type 'str'>>>> "St" + "ring" + " " + "Ma" + "th"'String Math'

Page 30: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Strings

• Python makes string formatting so simple.

>>> template = "My name is %s. I'm %d years old. I live in a %s that is %.3f %s high.">>> print templateMy name is %s. I'm %d years old. I live in a %s that is %.3f %s high.>>> template % ("Pilar", 25, "hibachi grill", 2/3.0, "angstroms")"My name is Pilar. I'm 25 years old. I live in a hibachi grill that is 0.667 angstroms high."

Page 31: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Lists

• Python provides easy to use lists.– Symbolized by a group of brackets: [ ]– Can contain zero or more objects of any type.– Dynamically add and delete items during

runtime.

Page 32: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Lists: Creating

• Lists are created with brackets:>>> x = [1,2,3]>>> x[1, 2, 3]>>> type(x)<type 'list'>>>> len(x)3

Page 33: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Lists: Test for Membership

• It's easy to find out if an element is in a list:>>> x = [1,2,3]>>> 1 in xTrue>>> 4 in XFalse>>> x.index(2)1

Page 34: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

List: Indexes

• Lists objects are indexed using the [] operator– Indexes start at zero

>>> x = [1, 2, 3]>>> x[1, 2, 3]>>> x[0]1>>> x[1]2>>> x[2]3

Page 35: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Lists and Strings

• You can relate strings and lists easily:

>>> x = "this is a string">>> x = x.split(" ")>>> x['this', 'is', 'a', 'string']>>> x[3] = "list">>> x['this', 'is', 'a', 'list']>>> str.join(" ", x)'this is a list'

Page 36: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

List: Deleting Indexes

• You can delete things from a list using indexes:

>>> x = [1, 2, 3]>>> x[1, 2, 3]>>> del x[0]>>> x[2, 3]

Page 37: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Lists: Slices

• You can get sub-list from a list using a colon in the index: [start index:end index]

>>> x = ['a', 'b', 'c', 'd', 'e']>>> x[2:4]['c', 'd']>>> x[0:2]['a', 'b']>>> x[:-2]['a', 'b', 'c']

Page 38: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Tuples

• Tuples are exactly like lists, except they are immutable after you create them.

• Tuples are created with parenthesis:

>>> x = (1,2,3)>>> type(x)<type 'tuple'>

Page 39: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Tuples are Immutable

>>> x = (1, 2, 3)>>> x(1, 2, 3)>>> x[0] = 3Traceback (most recent call last): File "<stdin>", line 1, in ?TypeError: object does not support item assignment>>> del x[0]Traceback (most recent call last): File "<stdin>", line 1, in ?TypeError: object doesn't support item deletion

Page 40: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Dictionaries

• Dictionaries provides key, value lookup.– Also known as a hash table.– In python, symbolized by a pair of braces: { }– Can contain zero or more key value pairs of

almost any type.– Dictionary example:

• Key: An English Word• Value: A Definition for the Word

Page 41: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Dictionaries: Creating

• Dictionaries are created using braces:>>> x = {}>>> x{}>>> x = {1:2, 3:4, 5:6}>>> x.keys()[1, 3, 5]>>> x.values()[2, 4, 6]x >>> x{1: 2, 3: 4, 5: 6}

Page 42: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Dictionaries: Key Lookup

• Lookup is accomplished using the [] operator:

>>> x = {'Green':"something of a green color", "Red":"Something of a red color"}>>> x['Green']'something of a green color'>>> x['Blue']

Traceback (most recent call last): File "<pyshell#28>", line 1, in -toplevel- x['Blue']KeyError: 'Blue'

Page 43: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Sets

• Sets are sequences of unique items.

• Sets creation is done using the builtin type set:

>>> a = set('apple')>>> aset(['a', 'p', 'e', 'l'])>>> type(a)<type 'set'>

Page 44: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Sets

>>> a = set('apple')>>> b = set('oranges')>>> aset(['a', 'p', 'e', 'l'])>>> bset(['a', 'e', 'g', 'o', 'n', 's', 'r'])>>> a - b # subtraction: in a, not bset(['p', 'l'])>>> a | b # union: in a or bset(['a', 'e', 'g', 'l', 'o', 'n', 'p', 's', 'r'])>>> a & b # intersection: in a and bset(['a', 'e'])>>> a ^ b # xor: in a or b, not bothset(['g', 'l', 'o', 'n', 'p', 's', 'r'])

Page 45: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Flow control

• Python gives you standard and not so standard tools to alter the flow through a program– if, elif, else– Loops (while, for)– Functions

Page 46: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

if, else

• if clauses provide decision branches.– Clause must reduce to an integer– Non-zero value is True, executes first scope– Zero value is False, executes second scope

>>> if True:........print “it’s True!”else:........print “it’s False!”it’s True!

Page 47: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

if, elif, else

• With elif, chaining if statements is easy

>>> x = raw_input( “type something> “ )type something> hi>>> if len( x ) == 0:........print “You didn’t type anything!”elif len( x ) == 1:........print “Lazy, you only typed one character!”elif len( x ) == 2:........print “You used two fingers, woohoo.”else:........print “Three or mores keys stroked.”“You used two fingers, woohoo.”

Page 48: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

*sigh*

• Python does not support goto statements.

• Python does not support switch statements.

Page 49: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

for

• For loops are a bit different in python from other languages.– List based, not condition based– 0builtin function range() helpful when you just

want to count over a series of numbers>>> range(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range(10, 20)[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]>>> range(10, 20, 2)[10, 12, 14, 16, 18]

Page 50: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

for Loop Example

>>> for x in range(1,10):... print "%d is twice as big as %.3f" % (x,x/2.0)

1 is twice as big as 0.5002 is twice as big as 1.0003 is twice as big as 1.5004 is twice as big as 2.0005 is twice as big as 2.5006 is twice as big as 3.0007 is twice as big as 3.5008 is twice as big as 4.0009 is twice as big as 4.500

Page 51: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

for

• continue statement, like in C, continues the loop to the next iteration.

• break statement, like in C, breaks out of the running loop.

>>> cnt = 0>>> for x in range(10):.......if x % 2: continue.......if x == 9: break.......cnt += 1>>> cnt5

Page 52: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

while

• Python while loops work like C while loops:– The body of a while loop executes indefinitely

until:• The while loop clause evaluates to False• The code in the while loop executes a break

– while loops support continue and break in exactly the same way as for loops.

Page 53: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

while

>>> while x != 5:........x = x + 1........if x != 5:................print "x != 5"........else:................print "x == 5"

x != 5x != 5x != 5x != 5x == 5

Page 54: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

while

• While loop breaks>>> x = 97>>> while True:........x = x + 1........print "I am %d years old!" % x........if x == 100:................break

I am 98 years old!I am 99 years old!I am 100 years old!

Page 55: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Functions

• Functions allow a programmer to break up a program into chunks.– A python function takes zero or more input

values (known as parameters) and generates zero or more output values (known as return values).

– "Good" rule of thumb: If you write two chunks of code that have nearly overlapping responsibilities, wrap it into a function.

Page 56: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Function definition

• Defining a Function– Syntax is def FunctionName():

• Like everything else in python, the body of a function body is scoped by white space.

>>> def func1():....print "Hello from func1()"

>>> func1()Hello from func1()>>> func1()Hello from func1()

Page 57: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Functions: Parameters

• Function that takes a parameter.

• Python functions are weakly typed...

>>> def OddOrEven(value):....if value % 2:........print "Your value is odd"....else:........print "Your value is even"

>>> OddOrEven(3)Your value is odd>>> OddOrEven(2)Your value is even

Page 58: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Weak Typing

"Weak typing requires less effort of the programmer than strong typing, because the compiler or interpreter will implicitly perform certain value conversions. As a result of this, weakly typed programming systems catch fewer errors at compile time, which can make debugging harder."

- http://en.wikipedia.org/wiki/Weak_typing

Page 59: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Strong vs. Weak Typing

"A type is a narrow piece of information about your data. When you look at large programs that deal with a lot of strong typing, you see that many words are spent working around strong typing."

- Guido van Rossum on Strong vs Weak Typing

http://www.artima.com/intv/strongweak.html

Page 60: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Functions: Return Value

• Function that returns a value.>>> def square(value):....return value * value

>>> square(3)9>>> square(square(3))81>>> x = square(10)>>> x100

Page 61: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Modules

• Python “libraries” are implemented as modules.

• A single python source file represents a python module. They are one-to-one.

• If a python file (module) was named “pcode.py”, import it into another file with:

>>> import pcode>>>

Page 62: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Variations on Import

• You can import specific names from a modules namespace:

>>> from pcode import pfunction, pconstant

• You can import everything directly into your namespace:

>>> from pcode import *

• You can change the name of items you import:

>>> import pcode.pfunction as python_function

Page 63: Introduction to Python Programming Giles Hall Jan 10, 2006 SIPB IAP 2006

Where to get Modules

• Python Package Index– http://www.python.org/pypi

• Vaults of Parnassus: Python Resources, a very cool repository of Python software. – http://www.vex.net/parnassus/

• Google, Freshmeat, Source Forge– Be creative when looking for prior art. If you

can think of it, someone has probably written it already.