Download Cosc 4750

Document related concepts
no text concepts found
Transcript
Cosc 4750
Python
Python
• Python is a scripting language similar to Perl and
PHP
• But Python takes a minimalist approach.
– While Perl provides maximal approach. PHP is
somewhere in between.
• “features of the language interact in consistent and
limited ways, and follow naturally from a small
set of core concepts”
• Python can be defined as a object-oriented
scripting language.
What can you do with Python
•
•
•
•
System programming
GUIs
Internet Scripts
Component Integration
– Can be extended by C/C++ or embedded into C/C++.
On windows can be used like VB.
• Database Programming
• Numeric Programming with NumPy
• Gaming, Images, AI, XML, and more.
IDE User Interface
• Python comes with an IDE, Called IDLE
• Linux: idle
• Let you edit, run, browse, and debug Python programs
• Works in two parts
– An editor, uses syntax-directed colorization
– A shell, where output goes when running scripts form the editor.
• There are other IDEs for python, Komodo, PythonWorks,
PythonWin (comes with ActiveState’s ActivePyton), Visual
Python and more. See http://www.python.org
The Language
• Since you already know a several
langauges, like perl, c/c++, PHP. I use
those to describe Python.
• Like Perl # is a comment
– Comment starts at # and continue to the end of
line
Built-in object types
•
Numbers
– 3.1312, 123, 999L (long integers unlimited size), 3+4j (complex number literals),
•
Strings
– ‘spam’, “Jim’s”
•
Lists
– [1, [2, ‘three’], 4]
•
Dictionaries
– {‘food’: ‘spam’, ‘taste’: ‘yum’}
•
Tuples
– (1, ‘spam’, 4, ‘U’)
•
Files
– Text = open (‘eggs’, ‘r’).read()
Operators
• lamba args: expr (anonymous function
generation)
• or, and, not
• <, <=, >, >=, ==, <>, !=,
• |, ^, &, <<, >>, ~ (bitwise operations)
• -, +, *, %, /, // (int division), ** (power)
Variables
• Like perl and PHP variables come into
existence when they are assigned a value
• They don’t require anything special
characters to denote they are variables
• a=3
• b = ‘jim’
• c = 3 + 12 * 6
strings
• Single and double quoted strings are the
same
–
–
–
–
allows user to use ‘ and “ in strings
‘knight”s’, “knight’s”
you can also escape the them “knight\”s”
title = “meaning “ ‘of’ “ Life”
• Python automatically concatenates adjacent strings
or can use +
• ‘meaning of life’
strings (2)
• Tripe quotes for multiline Block strings
– saying = “””Always look
on the bright
side of life.”””
– saying contains ‘Always look\n on the bright\n side of
life.’
• Raw strings
– turns off all escape mechanism in the string
– r (upper or lower) before the string
– r’c:\new\test.dat’ makes it the literal string.
stings operations
• len(string variable) return the length of the string
• var = ‘-’*80
– comes out with 80 dashes in the string
• all strings can be used a arrays (like char[] in c)
– s = ‘spam’
– print s[0] #prints s
– print s[-2] #prints a
• slicing like perl range in strings or substringing
– t = s[1:3] #t=‘pa’ gets from element 1 to 3 non-inclusive
– t = s[1:] #t = ‘pam’
– t = s[:-1] #t = ‘spa’
string concatenation
• unlike perl, python won’t auto cast to
strings from other types or vise versa
• str = “42” + 1 # Error
• var = int(“42”) + 1 # var = 43
• str = “42” + str(1) #str = ‘421’
string formatting
• using similar format as printf
(in perl and C)
• %s string
• %c character
• %d decimal
• %i integer
• %u unsigned int
• %o octal
• %x hex
• %e floating point exponent
• %f floating point decimal
• %g either e or f
• %% literal %
• example
x = 1234
y = jim
z = 1.234
str = ‘int %d, str %s, floats %f, %e,
%g’ % (x, y, z, z,z)
str =‘int 1234, str jim, floats 1.234,
1.234+e00, 1.234
String methods
• This is a list of common methods
– assume S has a string value
– S.capitalize(), S.center(width), S.count(sub [, start [,end]]),
S.endswith(suffix, [,start [, end]]), S. epandtabes([tabsize]), S.find(sub
[,start [,end]]) , S.find(sub [,start [,end]]), S.isalnum(), S.isalpa(),
S.isdigit(), S.islower(), S.isspace(), S.isupper(), S.istitle()
– S.join(seq), S.ljust(width), S.lower(), S.lstrip(), S.replace(old, new [,
maxsplit]), S.rfind(sub [,start [,end]]), S.rindex(sub [,start [,end]]),
S.rjust(width), S.rstrip(), S.split( [sep [, maxsplit]]), S.splitlines(
[keepends]), S.startswith(prefix [,start [,end]]), S.strip(), S.swapcase(),
S.title(), S.translate(table [, delchars]), S.upper
• strings are immutable, so you can’t change them in-place
directly so S = S.toupper()
examples of string methods
•
replace can replace all, or spec number
–
–
–
•
find returns offset in string
–
•
L = list(S) #L = [‘s’, ‘p’, ‘a’, ‘m’, ‘x’, ‘y’]
join method a list into a string
–
–
•
x = S.find(‘x’) #x = 4
list return a list of the string (not a method)
–
•
S = ‘spammy’
S = S.replace(‘mm’, ‘xx’) # S=‘spaxxy’
S = S.replace(‘m’, ‘x’, 1) # S= ‘spamxy’
S = ‘’.join(L) # S = ‘spamxy’ NOTE the ‘’ to call join
S = S.join([‘X’, ‘Y’]) #s = ‘XspamxyY’
split method, defaults to white space
–
–
–
S = ‘ba ac ad’
L = S.split() # L = [‘ba’, ‘ac’, ‘ad’]
L = S.split(‘a’) #L = [‘b’, ‘ ‘, ‘c ‘, ‘d’]
lists
• What we normally think of as arrays, except it based on the
LISP.
–
–
–
–
–
–
–
–
–
uses the [] operators.
L1 = [] #empty list
L2 = [0,1,2,3] # for items, index 0 .. 3
L3 = [‘abc’, [‘def’, ‘ghi’]] # nested lists.
a = L2[1] #a = 1
a = L3[1][0] # a = ‘def’
L = L2[1:3] # L = [1,2] Remember not inclusive
L = L2 + L3 # concatenate the lists
L = L2 * 3 # repeat L2 3 times
lists (2)
•
for x in L2 Iteration in the list
– Written in perl: foreach $x (@L2) { $x …}
•
x in L2 #membership, return 1 if true
– Is the value of x in the list L2
•
•
•
•
•
•
•
•
•
L2.append(4) # put 4 at the end of the list
L2.extend([3,4,5]) # add 3, 4, 5 to the end of the list
L2.sort() # sorts the list ascending
L2.reverse() # reverse the elements in the list
a = L2.pop() # remove last element, put in a
del L2[i] # remove element I
del L2[1:3] #remove range, not inclusive
L2[1] = ‘hi’ #change element 1 to ‘hi’
L2[i:j] = [4,5,6] #slice assissment.
Dictionaries (2)
•
•
•
•
•
•
•
•
•
•
•
•
•
associate arrays in Perl. Hash variables.
D1 = {} #empty dictionary
D2 = {‘spam’: 2, ‘eggs’:3} #spam and eggs are the keys
D3 = {‘food’: {‘ham’:1, ‘egg’:2}} #nested
a = D[‘eggs’] # a = 3
D2[‘ham’] = 2 #new key and value ‘ham’:2
del D2[‘ham’] #removes key/value from dictionary
a = d[‘food’][‘ham’] #a = 1
len(D2) # returns the number of entries
L = D2.keys() #L contains a list of the keys
L = D2.values() #L contains a list of values
L = D2.items() #returns a list of tuples (key, value)
D1.update(D2) #add dictionary D2 to D1
tuples
• Work just like lists, except they can’t be
changed in place.
• t1 = (0,) #one item tuple (not an expression)
• t2 = (0, ‘Ni’, 1.2, 3)
• t2 = 0, ‘Ni’, 1.2, 3 #same as above
• ERROR: t[1] = 1
• otherwise same operations as list
file type
• Python has files a open type (like streams in C++), instead of just using
filehandes.
• output = open(‘/tmp/stuff’, ‘w’) #open stuff to write
• input = open(‘data’, ‘r’) #open data to read
• S = input.read() #read entire file into string variable
• S = input.read(N) #read N bytes
• S = input.readline() #read next line
• L = input.readlines() #read entire file into list of line strings
• output.write(S) #write string S to file
• output.writelines(L) #write all lines in list L to file
• output.close() #close file
Python and true/false
• Generally use this rule for true/false
• Numbers are true if nonzero
• Objects are true if nonempty
• Examples
“spam” true, “” false, [] false, () false, {}
false, 1 true, 0.0 false, None False
– None is like NULL or similar to undef from
perl
Comparisons and Equality
• S1= ‘spam’, S2 = ‘spam’
– S1 == S2 true, S1 is S2 true (but should be false)
• is operator test for object identity (is it the same object
• S1 = ‘a longer string’ S2=‘a longer string
– S1 == S2 true, S1 is S2 false
– Because python cache short strings, but not “longer”
strings
• L1 = [1, (‘a’, 3)] L2 = [1, (‘a’), 3]
L1 == L2 false, L1 < L2 false, L1 > L2 true
Some problems.
• Python uses underlying pointers for objects and
sometimes you may not think it should
• L = [1,2,3]
• M = [‘X’, L, ‘Y’] # M has [‘X’, [1,2,3], ‘Y’]
• L[1] = 0
• M now has [‘X’, [1,0,3], ‘Y’]
• To fix this
• M = [‘X’, L[:], ‘Y’] # M has [‘X’, [1,2,3], ‘Y’]
– Now L is not linked in M.
Statements
• quick list
–
–
–
–
–
–
–
print
for/else
break, continue
import, from
class
del
assert
if/elif/else
while/else
try/except/finally
def, return, yield
global
exec
assignments
spam = ‘SPAM’
spam, ham = ‘yum’, ‘YUM’ (Tuple form)
[spam, ham] = [‘yum, ‘YUM’] (list form)
spam = ham = ‘lunch’ Multiple-target
• Note spam and ham point to the same object!
print statement
• Works like perl’s print statement
• print “whatever “, variables, etc…
• print “whatever”,
– no end of line markers, waits for next print statement.
• To print to a file
log = open (‘log.txt’,’a’) #append mode
print >> log, “whatever”, variables, etc…
log.close()
Writing a script and Syntax rules
• There are no blocks boundaries {} like most
languages, instead they are detected automatically
– Based on indentation of statements under a header
• You MUST write indented code for blocks!!!!
– Header, “:”, indented statements
• The statement boundaries, there is no ;
– normally end of line, except in some cases
• we come back to this
Hello World script
#!/usr/bin/python
print “hello World!”
• In unix
– python hello.py or make it executable
if statements
• general format
if <test>:
#if test block
<statements> #block of statements
elif <test>: #optional elifs
<statements> #block of statements
else:
#optional else, note the “:”
<statements>#block of statements
if example
x = ‘Elmer fud’
if x == ‘roger’:
print “How’s Jessica?”
elif x == ‘bugs’:
print “What’s up doc?”
else:
print “Run away!
block delimiters
• example of indentation and blocks
x =1
if x:
y = 2
if y:
#if y is true
print ‘block 2’ #then print
print ‘block 1’
#outside if y:
print ‘outside of if block’
statement boundaries
• special cases where statements span lines
– any statement with (), {}, []
• If the open on 1 line, then it can continue lines until
the close is reached.
– A backslash (\) at the end of the line will
continue it to the next line
– literals “strings” can span lines
– and triple quotes are designed to span lines
statement boundaries (2)
• Maybe you don’t want to span lines with
statements…
– You can use semicolons to end statements
– Every doc and books says DO NOT, bad style
• x =1; y = 12; etc…
• Finally headers can have one statement
– if x==1: print “hello”
– Includes whiles, etc.. anything with a header
case/switch
• There is no case/switch statement in Python
– Instead multiway branching can use elif’s
– or Dictionary
branch = {‘spam’: 1.25, ‘ham’: 1.99, ‘eggs’: 0.99}
print branch.get(‘spam’, ‘Bad choice’)
– ouput is 1.25 If spam was there, output is Bad Choice
– Neither allow for multi matching of the data
• ie where you leave out the break in C/C++
loops
• General loop format
while <test>: #header
<statements>
[if <test>: ]break
#exit loop now
[if <test>: ]continue # jumps to loop header
else:
<statements> #only run if loop doesn’t exit on a
break statements. IE exits loop “normally”
note about <test>
• <test> is an expression that evals to true or
false
– There is a on things that python DO NOT allow
in a expersion: Assignments
– no while line = input.readline():
– Does however remove the bug, x = 1 in
expresions. But you have to return “classical”
loops.
loops (2)
• General format for the for loop
for <target> in <object>: #assign object to target
<statements>
[if <test>: ]break
#exit loop now
[if <test>: ]continue # jumps to loop header
else:
<statements> #only run if loop doesn’t exit on a
break statements. IE exits loop “normally”
for loop example
sum = 0
for x in [1,2,3,4]: #or as complex as needed
sum = sum = x
print x,
print sum
• output
1 2 3 4 10
loop example with files
for line in open(‘text.txt’).readlines():
print line
• open a file and prints out each line to stdout.
– Note there is a .xreadlines() method that reads
on demand, so large files, won’t file up
memory.
functions
• General format of a function
def <name> ([arg1,…,argN]):
<statements>
[return <value>]
• Functions are declared at runtime, so you can have
the same function name for 2 or more functions,
so long as only one function is declared at any
given point.
• A function can also be assigned to “variable”
– Othername = func; othername()
Function example
Def add (x, y):
return x + y; #no type, so x and y can be any type
var1 = 12; var2 = 1;
var3 = add(var1,var2) # var3 = 13
str1 = “hi “; str2 = “ there”
str3 = add(str1, str2) # str3= “hi there”
functions and scope
• variables/names defined inside a function are local
to the function
– note functions can be defined inside functions
– variables with the same name are shadowed in the
function.
• global variables can be accessed inside a function,
but must be declared global in order to change
them.
– Any global variables can be read, only declared inside
the function as global can be changed.
– uses the global reserved word.
functions and scope (2)
• example:
x = 99; z = 100
def func(y):
z = x +y #local z, gobal x, and parameter y
return z
def func2(y):
global x
z = (++x) +y
return z
a = func(1) #a = 100, x =99
b = func2(1) #a =101, x=100
A word about parameters
• Parameters are passed by assignment
– similar to pass by reference in C++
– this maybe the same way Java deals with parameters
• Since all variables are pointers to objects, so when
parameter’s object is changed, it changes the
calling variables object.
– The issue, there is not a name aliasing, so it a new
object is created, it won’t change the calling variable.
Different object.
A word about parameters (2)
• example
def changer (x, y):
x=2
y[0] = ‘spam’
X =1; L =[1,2]
changer(X, L)
#X is unchanged, L = [‘spam’, 2]
A word about parameters (3)
• Default parameters
– def func (x, a=1, str=“hi”):
– <statements>
– func(12)# a =1, str=“hi”
• Keyword for parameters
– func(12, str=“There”) #x=12, a=1, str=“There”
A word about parameters (4)
• Arbitrary arguments
• Uses * or ** depending on how you want to see it.
– * args are a list
• def func( *arg):
• <statements> #arg = ( )
• func(1,2,3) #arg would be (1,2,3)
– ** args are in a dictionary
• def func(**arg):
• <statements>
• Func(x=1, y=2, z=12) # arg (x:1, y:2, z:12)
Anonymous Functions: Lamba
• General form
• variable = lamba arg1, …, argN: <expression>
– Note they is not a statement block
•
•
•
•
Example:
def func(x,y,z): return x+y+z #function
f = lamaba x,y,z: x + y +z #lamba function
Calling the function just like you set a function “equal” to
another variable.
– x= f(1,2,3) #x = 6
• lamba function can be nested.
modules
• use the import command and the name of
the module
• example
– Import os
– imports the os module with a number of
function to interact with the filesystem.
regular expressions
• Can you do then just the simple match, but
the expressions seem to follow their own
special language instead of the standards.
• uses module re
Some useful modules
• urllib and urlpase
– modules for Universal resource locators
• htmllib, mimetools, mimetypes, mail, uu
– lots of modules to how internet file processing
• xml.parses.expat, xml.dom, etc…
– xml processing
Not covered in this lectures
• building classes and OOP design
– inheritance
• exception handling
– type/except/else
– similar to java’s try/caught
• creating modules
Embedding Python
• In C/C++
#include <Python.h>
…
Py_Initialize();
PyRun_SimpleString(“x = brave + sir + robon”);
/* run code snippet See the python doc’s for more, C
programs may also gain access to Python objects,
process or execute them using other Python API
tools.
References
• http://www.python.org/
• Learning Python, Lutz & Ascher, O’Reilly,
2rd, 2003
Q&A