Download intro_to_python

Document related concepts
no text concepts found
Transcript
SIPB IAP 2006
Introduction to Python
Programming
Giles Hall <[email protected]>
Jan 10, 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.
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.
What’s So Good About It?
•
•
•
•
•
•
Free (http://www.python.org/)
Open source
Portable
Modern
Well documented
Robust
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.
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
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.
Python On The Web
http://www.python.org
-
Python Runtime
Documentation
Anything else, very helpful!
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
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
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 win32
Type "copyright", "credits" or "license()" for more information.
>>> 1
1
>>> 2
2
>>> 1 + 2
3
>>> "hi"
'hi'
Scope
• Python uses indentation to define a scope
>>> if (variable == True):
........print "It's True!"
else:
........print "It's not True!“
It's True!
Classic Python
• It's easy to compute the Fibonacci series:
>>> a, b = 0, 1
>>> while b < 10:
........print b
........a, b = b, a+b
1
1
2
3
5
8
- http://docs.python.org/tut/node5.html
True, False
• True and False are defined for you.
>>> True
True
>>> False
False
>>> True == False
False
>>> 1 == 1
True
More on True and False
• True and False are variables representing
1 and 0, but are not integers themselves:
>>> True
True
>>> 1
1
>>> 1 == True
True
>>> 2 == True
False
>>> 0 == False
True
Boolean Operators
• Boolean and
>>> True and False
False
>>> True and True
True
• Boolean or
>>> 1 or 0
1
• Boolean operator not
>>> not True
False
Calculator
• Python is a Useful Calculator
>>> 365 * 24 * 60 * 60
31536000
>>> 100 / 25
4
>>> 3.14 * 7 ** 2
153.86000000000001
>>> 3 % 2
1
>>> 3 % 3
0
Integer vs. Float
• Python differentiates floats from integers:
>>> 3 / 2
1
• A decimal zero will coerce python to
preserve the decimal in the result:
>>> 3 / 2.0
1.5
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
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'
Variables
• Python provides a global namespace to
associate data with variables.
>>> a = 1
>>> b = 2
>>> a + b
3
>>> x = “Good"
>>> y = “Bad"
>>> x + y
‘GoodBad'
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}
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.
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.
Example use of del
>>> x = 1
>>> x
1
>>> del x
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'x' is not defined
Types
• Python associates type information with
real-data:
>>> x = 1
>>> type(x)
<type 'int'>
>>> type(1.1)
<type 'float'>
>>> type(True)
<type 'bool'>
• Python provides a slew of builtin types,
including a variety of data structures...
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
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.
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'
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 template
My 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."
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.
Lists: Creating
• Lists are created with brackets:
>>> x = [1,2,3]
>>> x
[1, 2, 3]
>>> type(x)
<type 'list'>
>>> len(x)
3
Lists: Test for Membership
• It's easy to find out if an element is in a list:
>>> x = [1,2,3]
>>> 1 in x
True
>>> 4 in X
False
>>> x.index(2)
1
List: Indexes
• Lists objects are indexed using the []
operator
– Indexes start at zero
>>>
>>>
[1,
>>>
1
>>>
2
>>>
3
x = [1, 2, 3]
x
2, 3]
x[0]
x[1]
x[2]
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'
List: Deleting Indexes
• You can delete things from a list using
indexes:
>>>
>>>
[1,
>>>
>>>
[2,
x = [1, 2, 3]
x
2, 3]
del x[0]
x
3]
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']
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'>
Tuples are Immutable
>>> x = (1, 2, 3)
>>> x
(1, 2, 3)
>>> x[0] = 3
Traceback (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
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
Dictionaries: Creating
• Dictionaries are created using braces:
>>>
>>>
{}
>>>
>>>
[1,
>>>
[2,
x
>>>
{1:
x = {}
x
x = {1:2, 3:4, 5:6}
x.keys()
3, 5]
x.values()
4, 6]
x
2, 3: 4, 5: 6}
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 -toplevelx['Blue']
KeyError: 'Blue'
Sets
• Sets are sequences of unique items.
• Sets creation is done using the builtin type
set:
>>> a = set('apple')
>>> a
set(['a', 'p', 'e', 'l'])
>>> type(a)
<type 'set'>
Sets
>>> a = set('apple')
>>> b = set('oranges')
>>> a
set(['a', 'p', 'e', 'l'])
>>> b
set(['a', 'e', 'g', 'o', 'n', 's', 'r'])
>>> a - b
# subtraction: in a, not b
set(['p', 'l'])
>>> a | b
# union: in a or b
set(['a', 'e', 'g', 'l', 'o', 'n', 'p', 's', 'r'])
>>> a & b
# intersection: in a and b
set(['a', 'e'])
>>> a ^ b
# xor: in a or b, not both
set(['g', 'l', 'o', 'n', 'p', 's', 'r'])
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
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!
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.”
*sigh*
• Python does not support goto statements.
• Python does not support switch
statements.
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]
for Loop Example
>>> for x in range(1,10):
... print "%d is twice as big as %.3f" % (x,x/2.0)
1
2
3
4
5
6
7
8
9
is
is
is
is
is
is
is
is
is
twice
twice
twice
twice
twice
twice
twice
twice
twice
as
as
as
as
as
as
as
as
as
big
big
big
big
big
big
big
big
big
as
as
as
as
as
as
as
as
as
0.500
1.000
1.500
2.000
2.500
3.000
3.500
4.000
4.500
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
>>> cnt
5
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.
while
>>> while x != 5:
........x = x + 1
........if x != 5:
................print "x != 5"
........else:
................print "x == 5"
x
x
x
x
x
!=
!=
!=
!=
==
5
5
5
5
5
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!
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.
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()
Functions: Parameters
• Function that takes a parameter.
>>> 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
• Python functions are weakly typed...
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
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
Functions: Return Value
• Function that returns a value.
>>> def square(value):
....return value * value
>>>
9
>>>
81
>>>
>>>
100
square(3)
square(square(3))
x = square(10)
x
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
>>>
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
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.