Beruflich Dokumente
Kultur Dokumente
Presented by
Reg Charney
Charney@CharneyDay.com
Beginners' Python
Agenda
Python References
Python Advantages
Python Toolkit
Getting Python
Running Python
Python Principles
Python Language and Examples
Beginners' Python
References
Python Advantages
Object-Oriented
Dynamic Type Checking makes it
inherently generic C++ templates for
free!
Free, as in Open Source free
Portable
Powerful language constructs / features
Powerful toolkit / library
Mixable with other languages
Easy to use & learn
Beginners' Python
Python Toolkit
Dynamic typing
Built-in object types
Built-in tools
Library utilities
Third-party utilities
Automatic memory management
Programming-in-the-large support
Beginners' Python
System utilities
GUIs using Tkinter
Component integration
Rapid prototyping
Internet scripting
Database programming
Beginners' Python
Getting Python
On the Web:
www.python.org
Beginners' Python
C:> python
>>> print 2*3
6
Interactive prompt
No statement
delimiter
Python defined as an
environment variable
Beginners' Python
10
#include <Python.h>
// . . .
Py_Initialize();
PyRun_SimpleString("x=pfx+root+sfx");
// . . .
Platform-specific invocation
11
Simple examples
12
Python Principles
Beginners' Python
13
Can be
indexed/sliced?
Can be changed in
place?
Ordere
d
Mutabl
e
Examples
Numbers
N/A
No
Strings
Yes
No
Lists
Yes
Yes
Dictionari
es
No
Yes
{'hang':'man', 'fur':'ball'}
Tuples
Yes
No
Files
N/A
N/A
text = open('ham','r').read()
Beginners' Python
14
Operator Precedence
Low
Operators
Description
x and y
not x
Logical negation
<, <=, >, >=, ==, <>, !=, is, is not, in,
not in
x|y
Bitwise OR
x^y
Bitwise EXCLUSIVE OR
x&y
Bitwise AND
x << n, x >> n
x + y, x y
x * y, x / y, x % y
Beginners' Python
15
>>> A = 1; a = 2; A+a
3
Semicolons separates
statements on the same
line
Beginners' Python
16
Beginners' Python
17
Beginners' Python
18
Result
Description
1 / 2.0
x=1
x << 2, x | 2
1
(4, 3)
2 + -5j, 1j * 1J
2 + 3j * 2
(2+3j) * 3
Complex numbers
((2-5j), (-1+0j))
(2+6j)
(6+9j)
Beginners' Python
19
Strings
('a', 'b')
"""Spans two
lines"""
'Spans two\012lines'
'a' * 3 + 'b'
'aaab'
('a' + 'b') * 3
'ababab'
Beginners' Python
20
'abc'[2]
'c'
Range includes
lower bound and
excludes upper
bound
Index (zero based)
'abc'[1:]
'bc'
Slice to end
'abc'[:-1]
'ab'
'abc'[1:2]
'b'
Slice in middle
len('abc')
Length
for i in 'abc':
print i,
a b c
Iteration
'b' in 'abc'
String Operations
Beginners' Python
Adjacent strings
are
concatenated,
like in C
String Formatting
Beginners' Python
22
Lists (1)
[1, 2, 3][1:2]
[2]
[1, 5, 3]
[1, 3]
L.append(7); L
[1, 3, 7]
Beginners' Python
23
Lists (2)
[1, 3, 'a']
>>> L
[1, 3, 'a']
Beginners' Python
24
Lists (3)
Shared references
>>> X = [1 ,2, 3]
>>> L = ['a', X, 'c']; L
['a', [1, 2, 3], 'c']
>>> X[1] = -9; X, L
([1, -9, 3], ['a', [1, -9, 3], 'c'])
>>> M = X[:] # make copy of X
>>> X[0] = 'c'; X, M
(['c', 2, 3], [1, 2, 3])
Beginners' Python
25
Dictionaries
D['a'], D['b']
D.keys(), len(D)
(['b', 'a'], 2)
D.has_key('a')
D['c']=list('xy'); D {'b':[2,3],c:['x','y'],'a':1}
D.values()
del D['b']; D
26
Used to distinguish
tuple from expression
Tuples
(2, 3)
tuple(t[0]) + t
u = ('c',), u
('c')
Beginners' Python
27
Comparisons, Equality
False
Non-zero numeric: 1
True
False
None
False
Beginners' Python
28
Files
29
Reserved Words
and
assert
break
class
continue
except
def
del
elif
else
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
raise
return
try
while
Beginners' Python
30
Statements
Statements normally go to a = "xxx" #comment
the end of line
Statements can be continued across lines if:
There is an open syntactic unit: (), [],
{}
a = [1, # comment1
2] # comment2
b = 'a' \
'b'
c = """This is
a triple quote"""
Multiple statements
separated by semicolons (;)
on same line Beginners' Python
d = "abc"; print d
31
Assignment Statement
Defines variables names referring to
objects
Forms RHS tuples and assigns pair-wise
to LHS
Implicit assignments: import, from,
class,
for,
function,
adef,
= "Normal
assign";
a
'Normal assign'
argument,
etc.
[a,
b] = [1, 2];
a, b
(1, 2)
(2, 1)
a = b = "men"; b = "mice"; a, b
('men', 'mice')
a b c
Beginners' Python
32
Required after
conditional and else
IF Statement
Beginners' Python
33
Required after
conditional and
else
Beginners' Python
34
Truth Tests
(0, 1, 1)
(4, [])
[] and {}
[]
(3 < 2) or (0,), [] or {}
((0,), {})
Beginners' Python
35
WHILE Statement
General format:
while <test> :
<stmt-block1>
else :
<stmt-block2>
# loop conditional
# loop body
# optional - run
# if no break used
a = 0; b = 5
while a < b :
print a,
# outputs 0 1 2 3 4
a = a + 1
Beginners' Python
36
37
y = 2
while y < 10 :
y = y + 1
if y % 2 == 0 : continue # only do odd #s
x = y / 2
while x > 1 :
if y % x == 0 :
print "%d has factor %d" % (y, x)
break
# causes else to be skipped
x = x 1
else :
print "%d is prime" % y
Beginners' Python
38
FOR Statement
General format:
for <target> in
<stmt-block1>
else :
<stmt-block2>
sum = 0
for x in [1, 2, 3, 5] : sum = sum + x
sum
# outputs 11
Beginners' Python
39
Beginners' Python
40
RANGE Function
Beginners' Python
41
Statement Gotchas
42
Named Functions
General format:
43
44
Scope Rules
def outer(n) :
def inner(n) :
if n > 1 :
return n * inner(n-1) # err does not
else:
# know own name
return 1
return inner(n)
Beginners' Python
46
def outer(n) :
global inner
# put name in global scope
def inner(n) :
if n > 1 :
return n * inner(n-1) # finds name by
else:
# LGB rule
return 1
return inner(n)
Beginners' Python
47
GLOBAL Statement
A = [1, 2]; B = []
C = {'Ann':'M'}
def F(X) :
print "Before: X=%s C=%s" % (X, C)
X.append(A)
C['Ann'] = 'F' # allowed to change sub-object
global C
# needed to change global C
C = {}
# illegal without global stmt
print "After: X=%s C=%s" % (X, C)
F(B)
# changes B to [1, 2]
Beginners' Python
48
RETURN Statement
def wow(x, y) :
x = 2 * x
y = 3 * y
return x, y
X = ['Hi']
Y = ('a')
A, B = wow(X, Y)
>>> A, B
(['Hi', 'Hi'], 'aaa')
Beginners' Python
49
Beginners' Python
50
Where
Description
F(val)
Caller
Matched by position.
F(name=val)
Caller
Matched by name.
def F(name) :
Definitio
n
Position parameter.
def
F(name=val) :
Definitio
n
def F(*name) :
Definitio
n
def F(**name) :
Definitio
n
Argument Matching
Example
>>> w(unknown='a', 5)
Beginners' Python
52
LAMBDA Expressions
Example:
APPLY Built-in
apply(fcn, args)
Example:
54
MAP Built-in
map(fcn, sequence)
Example:
Beginners' Python
55
Function Gotchas
def f():
print B
B = 2;
Beginners' Python
56
Modules (1)
Beginners' Python
57
Modules (2)
58
Loading Modules
Description
import mymod
Reload(mymod)
59
Qualified names
counter = 1
>>> sigma1.counter
def Sigma(L) :
sum = 0
return sum
>>> sigma1.counter = 2
Beginners' Python
60
Qualified Names
Beginners' Python
62
A = 1; C = 2; D = 4; # no B defined
>>> A = 99; B = 98; C = 97; D = 96
>>> from ModA import A, C
>>> print A, B, C, D
1 98 2 96
63
import mymod
name1 = mymod.name1
name2 = mymod.name2
. . .
del mymod
Beginners' Python
64
65
import mymod
. . .
reload(mymod)
Beginners' Python
66