SLIDES ANNO GIUSTIZIA DEFINITIVO · 2015. 7. 9. · *,867,=,$ '/ '/ 81$112',*,867,=,$
PythonPython Csc 667/867 Course note credit to PrenticeHall.
-
date post
19-Dec-2015 -
Category
Documents
-
view
239 -
download
3
Transcript of PythonPython Csc 667/867 Course note credit to PrenticeHall.
PythonPythonPythonPython
Csc 667/867Csc 667/867
Course note credit to PrenticeHall
2
Printing a Line of Text
• Python Online Tutorialhttp://www.python.org/doc/current/tut/
• Python Reference Manualhttp://docs.python.org/ref/contents.html
• Executing– Saving as a file
• Type code into a .py file and save it• To run it type python fileName.py
– Executing code
• Type python in the command line• Runs the python interpreter
3
Adding Integers
• Functions– The raw_input function
• Used to retrieve data from the user
– The int function• Used to convert strings to integers
4
1 1 # Fig. 2.7: fig02_07.py# Fig. 2.7: fig02_07.py
2 2 # Simple addition program.# Simple addition program.
3 3
4 4 # prompt user for input# prompt user for input
55 integer1 = raw_input( integer1 = raw_input( "Enter first integer:\n""Enter first integer:\n" ) ) # read string# read string
6 6 integer1 = int( integer1 ) integer1 = int( integer1 ) # convert string to integer# convert string to integer
7 7
8 8 integer2 = raw_input( integer2 = raw_input( "Enter second integer:\n""Enter second integer:\n" ) ) # read string# read string
99 integer2 = int( integer2 ) integer2 = int( integer2 ) # convert string to integer# convert string to integer
10 10
1111 sum = integer1 + integer2 sum = integer1 + integer2 # compute and assign sum# compute and assign sum
12 12
13 13 printprint "Sum is""Sum is", sum , sum # print sum# print sum
Enter first integer:
45
Enter second integer:
72
Sum is 117
5
Another Program: Adding Integers
Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> value1 = raw_input( "Enter an integer: " )
Enter an integer: 2
>>> value2 = raw_input( "Enter an integer: " )
Enter an integer: 4
>>> print value1 + value2
24
Fig. 2.8 Adding values from raw_input (incorrectly) without converting to integers (the result should be 6).
6
Arithmetic• Symbols
– * = multiply– / = divide– % = modulus– ** = exponential– // = floor division
• Only available in Python 2.2• Must use from __future__ import division
• Order– Operators are done in order of parenthesis,
exponents, multiple and divide (left to right), and lastly add and subtract (left to right)
7
Arithmetic
Operator(s) Operation(s) Order of Evaluation (Precedence)
( ) Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
** Exponentiation Evaluated second. If there are several, they are evaluated right to left.
* / // % Multiplication Division Modulus
Evaluated third. If there are several, they are
evaluated left to right. [Note: The // operator is new in version 2.2]
+ - Addition Subtraction
Evaluated last. If there are several, they are evaluated left to right.
Fig. 2.16 Precedence of arithmetic operators.
8
Augmented Assignment Symbols
Assignment symbol
Sample expression
Explanation Assigns
Assume: c = 3, d = 5, e = 4, f = 2, g = 6, h = 12
+= c += 7 c = c + 7 10 to c
-= d -= 4 d = d - 4 1 to d
*= e *= 5 e = e * 5 20 to e
**= f **= 3 f = f ** 3 8 to f /= g /= 3 g = g / 3 2 to g
%= h %= 9 h = h % 9 3 to h
Fig. 3.16 Augmented arithmetic assignment symbols.
9
Logical Operators• Operators
– and• Evaluates to true if both expressions are true
– or• Evaluates to true if at least one expression is true
– not• Returns true if the expression is false• Not required in any program
10
String Formatting• Strings
– Unlike other languages strings are a built in data type
• Allows for easy string manipulation
– Double quote strings• Single quotes need not be escaped
– Single quote strings• Double quotes need not be escaped
– Triple quoted strings• Do not need any escape sequence• Used for large blocks of text
11
1 1 # Fig. 2.18: fig02_18.py# Fig. 2.18: fig02_18.py2 2 # Creating strings and using quote characters in strings.# Creating strings and using quote characters in strings.3 3 4 4 printprint "This is a string with \"double quotes.\"" "This is a string with \"double quotes.\""55 printprint 'This is another string with "double quotes."' 'This is another string with "double quotes."'6 6 printprint 'This is a string with \'single quotes.\'' 'This is a string with \'single quotes.\''77 printprint "This is another string with 'single quotes.'" "This is another string with 'single quotes.'"88 printprint """This string has "double quotes" and 'single quotes'. """This string has "double quotes" and 'single quotes'.9 9 You can even do multiple lines.""" You can even do multiple lines."""10 10 printprint '''This string also has "double" and 'single' quotes.''' '''This string also has "double" and 'single' quotes.'''
This is a string with "double quotes."
This is another string with "double quotes."
This is a string with 'single quotes.'
This is another string with 'single quotes.'
This string has "double quotes" and 'single quotes'.
You can even do multiple lines.
This string also has "double" and 'single' quotes.
12
2 2 # String formatting.# String formatting.3 3 4 4 integerValue =integerValue = 4237 42375 5 printprint "Integer ""Integer ", integerValue, integerValue6 6 printprint "Decimal integer %d""Decimal integer %d" % integerValue % integerValue7 7 printprint "Hexadecimal integer %x\n""Hexadecimal integer %x\n" % integerValue % integerValue8 8 9 9 floatValue =floatValue = 123456.789 123456.78910 10 printprint "Float""Float", floatValue, floatValue11 11 printprint "Default float %f""Default float %f" % floatValue % floatValue1212 printprint "Default exponential %e\n""Default exponential %e\n" % floatValue % floatValue13 13 14 14 printprint "Right justify integer (%8d)""Right justify integer (%8d)" % integerValue % integerValue1515 printprint "Left justify integer (%-8d)\n""Left justify integer (%-8d)\n" % integerValue % integerValue16 16 17 17 stringValue = stringValue = "String formatting""String formatting"18 18 printprint "Force eight digits in integer %.8d""Force eight digits in integer %.8d" % integerValue % integerValue19 19 printprint "Five digits after decimal in float %.5f""Five digits after decimal in float %.5f" % floatValue % floatValue20 20 printprint "Fifteen and five characters allowed in string:""Fifteen and five characters allowed in string:"2121 printprint "(%.15s) (%.5s)""(%.15s) (%.5s)" % ( stringValue, stringValue ) % ( stringValue, stringValue )
13
Integer 4237
Decimal integer 4237
Hexadecimal integer 108d
Float 123456.789
Default float 123456.789000
Default exponential 1.234568e+005
Right justify integer ( 4237)
Left justify \integer (4237 )
Force eight digits in integer 00004237
Five digits after decimal in float 123456.78900
Fifteen and five characters allowed in string:
(String formatti) (Strin)
14
Indentation• Indenting
– Used to delimit code– Python uses no end of statement character– Therefore a new line of code is determined by return
space– Indenting is the same way
• Python does not use {} to enclose a multi-line statement
• The indentation must be exactly the same same
– There is no exact rule for the number of spaces but they are generally in groups of three
15
Lines• Logical Lines (
http://docs.python.org/ref/logical.html)• Physical Lines • Explicit Line Joining
• Implicit Line Joining
if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
return 1
month_names = ['Januari', 'Februari', 'Maart', # These are the 'April', 'Mei', 'Juni', # Dutch names 'Juli', 'Augustus', 'September', # for the months 'Oktober', 'November', 'December'] # of the year
16
Control Structure• Sequential order
– Statements are executed in the order they are written• Transfer of control
– A program executes a statement other than the following one
– The goto statement• Allows a program to go to a wide range of areas in the code• Structured programming was broken with the use of goto• Any code can be written without a goto statement
– Selection structure• The if statement• The if/else statement• The if/elif/else statement
– Repetition structure• The while repetition structure• The for repetition structure
17
11 # Control Statement examples# Control Statement examples22 # Class average program with counter-controlled # Class average program with counter-controlled repetition.repetition.3344 # initialization phase# initialization phase55 total =total = 0 0 # sum of grades# sum of grades66 gradeCounter =gradeCounter = 1 1 # number of grades entered# number of grades entered7788 # processing phase# processing phase99 whilewhile gradeCounter <= gradeCounter <= 10 10: : # loop 10 times# loop 10 times1010 grade = raw_input( grade = raw_input( "Enter grade: ""Enter grade: " ) ) # get one grade# get one grade1111 grade = int( grade ) grade = int( grade ) # convert string to an integer# convert string to an integer1212 total = total + grade total = total + grade1313 gradeCounter = gradeCounter + gradeCounter = gradeCounter + 1 114141515 # termination phase# termination phase1616 average = total /average = total / 10 10 # integer division# integer division1717 printprint "Class average is""Class average is", average, average
18
11 # More control statement example# More control statement example22 # Class average program with sentinel-controlled # Class average program with sentinel-controlled repetition.repetition.3344 # initialization phase# initialization phase55 total =total = 0 0 # sum of grades# sum of grades66 gradeCounter =gradeCounter = 0 0 # number of grades entered# number of grades entered7788 # processing phase# processing phase99 grade = raw_input( grade = raw_input( "Enter grade, -1 to end: ""Enter grade, -1 to end: " ) ) # get one # get one gradegrade1010 grade = int( grade ) grade = int( grade ) # convert string to an integer# convert string to an integer11111212 whilewhile grade != grade != -1-1::1313 total = total + grade total = total + grade1414 gradeCounter = gradeCounter + gradeCounter = gradeCounter + 1 11515 grade = raw_input( grade = raw_input( "Enter grade, -1 to end: ""Enter grade, -1 to end: " ) )1616 grade = int( grade ) grade = int( grade )17171818 # termination phase# termination phase1919 ifif gradeCounter != gradeCounter != 0 0::2020 average = float( total ) / gradeCounter average = float( total ) / gradeCounter2121 printprint "Class average is""Class average is", average, average2222 elseelse::2323 printprint "No grades were entered""No grades were entered"
19
break and continue Statements
• The break statement– Used to make a loop stop looping– The loop is exited and no more loop code is
executed
• The continue statement– Used to continue the looping process– All following actions in the loop are not executed
• But the loop will continue to run
20
1 1 # Fig. 3.24: fig03_24.py# Fig. 3.24: fig03_24.py
2 2 # Using the break statement in a for structure.# Using the break statement in a for structure.
3 3
44 forfor x x inin range( range( 1 1,, 11 11 ): ):
5 5
6 6 ifif x == x == 5 5::
77 breakbreak
8 8
9 9 printprint x, x,
10 10
1111 printprint "\nBroke out of loop at x =""\nBroke out of loop at x =", x, x
1 2 3 4Broke out of loop at x = 5
21
Logical Operators
Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> if 0:... print "0 is true"... else:... print "0 is false"...0 is false>>> if 1:... print "non-zero is true"...non-zero is true>>> if -1:... print "non-zero is true"...non-zero is true>>> print 2 < 31>>> print 0 and 10>>> print 1 and 33
Fig. 3.28 Truth values.
22
Variable Scopedef demo (f_in):
global somevar # shared with main codedemo.tom = 16 # An attribute accessible from main codesomevar += 1f_in = 2demo.another = 12 # A local variable, independent of main codeanother = 13res = f_in+14 # Value passed in (f_in)return res
somevar = 27 # accessed in function via globalanother = 17 # not accessed in functionpval = 16 # accessed in function via parameter
print demo(pval) print pvalprint demo.tom # function attributeprint somevarprint anotherprint demo.another
23
Using Lists
Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> aList = [ 1 ]>>> print aList[ 13 ]Traceback (most recent call last): File "<stdin>", line 1, in ?IndexError: list index out of range
Fig. 5.4 Out-of-range error.
24
1 1 # Fig. 5.5: fig05_05.py# Fig. 5.5: fig05_05.py2 2 # Creating a histogram from a list of values.# Creating a histogram from a list of values.3 3 4 4 values = [] values = [] # a list of values# a list of values5 5 6 6 # input 10 values from user# input 10 values from user7 7 printprint "Enter 10 integers:""Enter 10 integers:"8 8 9 9 forfor i i inin range( range( 10 10 ): ):10 10 newValue = int( raw_input( newValue = int( raw_input( "Enter integer %d: ""Enter integer %d: " % ( i + % ( i + 1 1 ) ) ) ) ) )1111 values += [ newValue ] values += [ newValue ]12 12 13 13 # create histogram# create histogram14 14 printprint "\nCreating a histogram from values:""\nCreating a histogram from values:"15 15 printprint "%s %10s %10s""%s %10s %10s" % ( % ( "Element""Element", , "Value""Value", , "Histogram""Histogram" ) )16 16 17 17 forfor i i inin range( range( len( values ) ):len( values ) ):1818 printprint "%7d %10d %s""%7d %10d %s" % ( i, values[ i ], % ( i, values[ i ], "*""*" * values[ i ] ) * values[ i ] )
Fig05_05.pyFig05_05.pyProgram OutputProgram OutputFig05_05.pyFig05_05.py
Program OutputProgram Output
Enter 10 integers:Enter integer 1: 19Enter integer 2: 3Enter integer 3: 15Enter integer 4: 7Enter integer 5: 11Enter integer 6: 9Enter integer 7: 13Enter integer 8: 5Enter integer 9: 17Enter integer 10: 1 Creating a histogram from values:Element Value Histogram 0 19 ******************* 1 3 *** 2 15 *************** 3 7 ******* 4 11 *********** 5 9 ********* 6 13 ************* 7 5 ***** 8 17 ***************** 9 1 *
26
1 1 # Fig. 5.6: fig05_06.py# Fig. 5.6: fig05_06.py
2 2 # Creating and accessing tuples.# Creating and accessing tuples.
3 3
4 4 # retrieve hour, minute and second from user# retrieve hour, minute and second from user
5 5 hour = int( raw_input( hour = int( raw_input( "Enter hour: ""Enter hour: " ) ) ) )
6 6 minute = int( raw_input( minute = int( raw_input( "Enter minute: ""Enter minute: " ) ) ) )
7 7 second = int( raw_input( second = int( raw_input( "Enter second: ""Enter second: " ) ) ) )
8 8
99 currentTime = hour, minute, second currentTime = hour, minute, second # create tuple# create tuple
10 10
1111 printprint "The value of currentTime is:""The value of currentTime is:", currentTime, currentTime
12 12
13 13 # access tuple# access tuple
14 14 printprint "The number of seconds since midnight is", \ "The number of seconds since midnight is", \
1515 ( currentTime[ ( currentTime[ 0 0 ] * ] * 3600 3600 + currentTime[ + currentTime[ 1 1 ] * ] * 60 60 + +
1616 currentTime[ currentTime[ 2 2 ] ) ] )
Enter hour: 9Enter minute: 16Enter second: 1The value of currentTime is: (9, 16, 1)The number of seconds since midnight is 33361
27
1 1 # Fig. 5.09: fig05_09.py# Fig. 5.09: fig05_09.py
2 2 # Creating, accessing and modifying a dictionary.# Creating, accessing and modifying a dictionary.
3 3
4 4 # create and print an empty dictionary# create and print an empty dictionary
55 emptyDictionary = {}emptyDictionary = {}
6 6 printprint "The value of emptyDictionary is:""The value of emptyDictionary is:", emptyDictionary, emptyDictionary
7 7
8 8 # create and print a dictionary with initial values# create and print a dictionary with initial values
99 grades = { grades = { "John""John":: 87 87, , "Steve""Steve":: 76 76, , "Laura""Laura":: 92 92, , "Edwin""Edwin":: 89 89 } }
10 10 printprint "\nAll grades:""\nAll grades:", grades, grades
11 11
12 12 # access and modify an existing dictionary# access and modify an existing dictionary
13 13 printprint "\nSteve's current grade:""\nSteve's current grade:", grades[ , grades[ "Steve""Steve" ] ]
1414 grades[ grades[ "Steve""Steve" ] = ] = 90 90
15 15 printprint "Steve's new grade:""Steve's new grade:", grades[ , grades[ "Steve""Steve" ] ]
16 16
17 17 # add to an existing dictionary# add to an existing dictionary
1818 grades[ grades[ "Michael""Michael" ] = ] = 93 93
19 19 printprint "\nDictionary grades after modification:""\nDictionary grades after modification:"
20 20 printprint grades grades
21 21
22 22 # delete entry from dictionary# delete entry from dictionary
2323 deldel grades[ grades[ "John" "John" ]]
24 24 printprint "\nDictionary grades after deletion:""\nDictionary grades after deletion:"
25 25 printprint grades grades
28
The value of emptyDictionary is: {} All grades: {'Edwin': 89, 'John': 87, 'Steve': 76, 'Laura': 92} Steve's current grade: 76Steve's new grade: 90 Dictionary grades after modification:{'Edwin': 89, 'Michael': 93, 'John': 87, 'Steve': 90, 'Laura': 92} Dictionary grades after deletion:{'Edwin': 89, 'Michael': 93, 'Steve': 90, 'Laura': 92}
29
1 1 # Fig. 5.17: fig05_17.py# Fig. 5.17: fig05_17.py
2 2 # Sorting a list.# Sorting a list.
3 3
4 4 aList = [aList = [ 2 2,, 6 6,, 4 4,, 8 8,, 10 10,, 12 12,, 89 89,, 68 68,, 45 45,, 37 37 ] ]
5 5
6 6 printprint "Data items in original order""Data items in original order"
7 7
8 8 forfor item item inin aList: aList:
99 printprint item, item,
10 10
1111 aList.sort()aList.sort()
12 12
13 13 printprint "\n\nData items after sorting""\n\nData items after sorting"
14 14
15 15 forfor item item inin aList: aList:
1616 printprint item, item,
17 17
18 18 printprint
Data items in original order2 6 4 8 10 12 89 68 45 37 Data items after sorting2 4 6 8 10 12 37 45 68 89
30
List and Dictionary Methods
Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> dictionary = { "listKey" : [ 1, 2, 3 ] }>>> shallowCopy = dictionary.copy() # make a shallow copy>>> dictionary[ "listKey" ].append( 4 )>>> print dictionary{'listKey': [1, 2, 3, 4]}>>> print shallowCopy{'listKey': [1, 2, 3, 4]} >>> from copy import deepcopy>>> deepCopy = deepcopy( dictionary ) # make a deep copy>>> dictionary[ "listKey" ].append( 5 )>>> print dictionary{'listKey': [1, 2, 3, 4, 5]}>>> print shallowCopy{'listKey': [1, 2, 3, 4, 5]}>>> print deepCopy{'listKey': [1, 2, 3, 4]}
Fig. 5.15 Difference between a shallow copy and a deep copy.
31
Modules• Check
http://www.python.org/doc/current/tut/node8.html• Import, from
• The Module Search Path – in the current directory– And then in the list of directories specified by the
environment variable PYTHONPATH # Fibonacci numbers module def fib(n):# write Fibonacci series up to n a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): # return Fibonacci series up to n result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result
Fibo.py
>>> import fibo >>> fibo.fib(1000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 >>> fibo.fib2(100) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]>>> fibo.__name__ 'fibo' If you intend to use a function often you can assign it to a local name: >>> fib = fibo.fib >>> fib(500) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
>>> from fibo import fib, fib2 >>> fib(500)
32
CGI modulehttp://docs.python.org/lib/module-cgi.html
form = cgi.FieldStorage() if not (form.has_key("name") and form.has_key("addr")):
print "<H1>Error</H1>" print "Please fill in the name and addr fields." return
print "<p>name:", form["name"].value print "<p>addr:", form["addr"].value …value = form.getlist("username") usernames = ",".join(value) …fileitem = form["userfile"]
33
1 1 #!c:\Python\python.exe#!c:\Python\python.exe
2 2 # Fig. 6.5: fig06_05.py# Fig. 6.5: fig06_05.py
3 3 # Program displaying CGI environment variables.# Program displaying CGI environment variables.
4 4 importimport os os
66 importimport cgi cgi
7 7
8 8 defdef printHeader( title ): printHeader( title ):
9 9 printprint """Content-type: text/html """Content-type: text/html <?xml version = "1.0" encoding = "UTF-8"?> <?xml version = "1.0" encoding = "UTF-8"?>
12 12 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
14 14 "DTD/xhtml1-strict.dtd"> "DTD/xhtml1-strict.dtd">
15 15 <html xmlns = "http://www.w3.org/1999/xhtml"><html xmlns = "http://www.w3.org/1999/xhtml">
16 16 <head><title>%s</title></head><body>"""<head><title>%s</title></head><body>""" % title % title
19 19 rowNumber =rowNumber = 0 0
21 21 backgroundColor = backgroundColor = "white""white"
23 23 printHeader( printHeader( "Environment Variables""Environment Variables" ) )
2424 printprint """<table style = "border: 0">""""""<table style = "border: 0">"""
25 25
26 26 # print table of cgi variables and values# print table of cgi variables and values
2727 forfor item item inin os.environ.keys(): os.environ.keys():
28 28 rowNumber += rowNumber += 1 1
30 30 ifif rowNumber % rowNumber % 2 2 == == 0 0: : # even row numbers are white# even row numbers are white
31 31 backgroundColor = backgroundColor = "white""white"
32 32 elseelse: : # odd row numbers are grey# odd row numbers are grey
33 33 backgroundColor = backgroundColor = "lightgrey""lightgrey"• printprint """<tr style = "background-color: %s">"""<tr style = "background-color: %s"> <td>%s</td><td>%s</td> <td>%s</td><td>%s</td>
• </tr>"""</tr>""" % ( backgroundColor,cgi.escape( item ), cgi.escape(os.environ[ item ])) % ( backgroundColor,cgi.escape( item ), cgi.escape(os.environ[ item ])) 3939 printprint """</table></body></html>""""""</table></body></html>"""
Function cgi.escape takes
a string and returns a properly
formatted XHMTL string
34
fig06_05.pyfig06_05.py
35
1 1 #!c:\Python\python.exe#!c:\Python\python.exe
2 2 importimport os os
6 6 importimport cgi cgi
7 7
8 8 defdef printHeader( title ): printHeader( title ):
9 9 printprint """Content-type: text/html"""Content-type: text/html
10 10
11 11 <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC
13 13 "-//W3C//DTD XHTML 1.0 Strict//EN“ "DTD/xhtml1-strict.dtd"> "-//W3C//DTD XHTML 1.0 Strict//EN“ "DTD/xhtml1-strict.dtd">
15 15 <html xmlns = "http://www.w3.org/1999/xhtml"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head><title>%s</title></head><head><title>%s</title></head>
17 17 <body>"""<body>""" % title % title
19 19
20 20 printHeader( printHeader( "QUERY_STRING example""QUERY_STRING example" ) )
21 21 printprint "<h1>Name/Value Pairs</h1>""<h1>Name/Value Pairs</h1>"
22 22
2323 query = os.environ[ query = os.environ[ "QUERY_STRING""QUERY_STRING" ] ]
24 24
25 25 ifif len( query ) == len( query ) == 0 0::
26 26 printprint """<p><br />"""<p><br />
27 27 Please add some name-value pairs to the URL above. Please add some name-value pairs to the URL above.
28 28 Or try <a href = "fig06_06.py?name=Veronica&age=23">this</a>. Or try <a href = "fig06_06.py?name=Veronica&age=23">this</a>.
30 30 </p>"""</p>"""
31 31 elseelse: :
32 32 printprint """<p style = "font-style: italic">"""<p style = "font-style: italic">
33 33 The query string is '%s'.</p>"""The query string is '%s'.</p>""" % cgi.escape( query ) % cgi.escape( query )
3434 pairs = cgi.parse_qs( query ) pairs = cgi.parse_qs( query )
35 35 forfor key, value key, value inin pairs.items(): pairs.items():
37 37 printprint "<p>You set '%s' to value %s</p>"""<p>You set '%s' to value %s</p>"" % \ % \
38 38 ( key, value ) ( key, value )
40 40 printprint "</body></html>""</body></html>"
36
37
1 1 #!c:\Python\python.exe#!c:\Python\python.exe
2 2 importimport cgi cgi
6 6
7 7 defdef printHeader( title ): printHeader( title ):
8 8 printprint """Content-type: text/html"""Content-type: text/html
9 9
10 10 <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC
12 12 "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
14 14 <html xmlns = "http://www.w3.org/1999/xhtml"><html xmlns = "http://www.w3.org/1999/xhtml">
15 15 <head><title>%s</title></head><head><title>%s</title></head>
16 16
17 17 <body>"""<body>""" % title % title
18 18
19 19 printHeader( printHeader( "Using 'post' with forms""Using 'post' with forms" ) )
20 20 printprint """<p>Enter one of your favorite words here:<br /></p>"""<p>Enter one of your favorite words here:<br /></p>
2121 <form method = "post" action = "fig06_09.py"> <form method = "post" action = "fig06_09.py">
22 22 <p><p>
23 23 <input type = "text" name = "word" /> <input type = "text" name = "word" />
24 24 <input type = "submit" value = "Submit word" /> <input type = "submit" value = "Submit word" />
25 25 </p></p>
26 26 </form>""" </form>"""
27 27
28 28 pairs = cgi.parse()pairs = cgi.parse()
29 29
30 30 ifif pairs.has_key( pairs.has_key( "word""word" ): ):
31 31 printprint """<p>Your word is:"""<p>Your word is:
32 32 <span style = "font-weight: bold">%s</span></p>"""<span style = "font-weight: bold">%s</span></p>""" \ \
33 33 % cgi.escape( pairs[ % cgi.escape( pairs[ "word""word" ][ ][ 00 ] ) ] )
34 34
35 35 printprint "</body></html>""</body></html>"
38
39
Cookie
• http://wp.netscape.com/newsref/std/cookie_spec.html– Set-Cookie: NAME=VALUE; expires=DATE;
path=PATH; domain=DOMAIN_NAME; secure – Cookie: NAME1=OPAQUE_STRING1;
NAME2=OPAQUE_STRING2 ...
• Response goes with “Set-Cookie” and then Request comes with “Cookie”
• Cookie example at unicorn.sfsu.edu/cgi-667/cookiecounter.py
40
#!/usr/bin/env python
from Cookie import SimpleCookieimport cgiimport os
def getCookie(initialvalues = {}): """Return a SimpleCookie. If some of the cookie values haven't been set, we'll plunk them into the cookie with the initialValues dict.""" if os.environ.has_key('HTTP_COOKIE'): C = SimpleCookie(os.environ['HTTP_COOKIE']) else: C = SimpleCookie() for key in initialvalues.keys(): if not C.has_key(key): C[key] = initialvalues[key] return C
if __name__ == '__main__': cookie = getCookie({'counter': 0}) cookie['counter'] = int(cookie['counter'].value) + 1
print cookie print "content-type: text/plain\n\n"
print "Here's our count:", cookie['counter'].value
Check http://docs.python.org/lib/module-Cookie.html for detail information for cgi module
41
Sequences• Sequence
– Series of items that are often related– Strings are sequences in Python– A sequence is returned by the range function– Elements
• The individual items in each sequence– Referred to by subscripts
• The first is always zero• Obtain one by using sequenceName[ subscript ]• Can also be referred to negatively
– -1 would be the last element of the sequence
42
Sequences
Fig. 5.1 Sequence with elements and indices.
-45
6
0
72
1543
-89
0
62
-3
1
6453
-78c[ 11 ]
c[ 10 ]
c[ 9 ]
c[ 8]
c[ 7 ]
c[ 4 ]
c[ 3 ]
c[ 2 ]
c[ 1 ]
c[ 0 ]
c[ 6 ]
c[ 5 ]
Position number of the element within sequence c
Name sequence (c)
c[ -1 ]
c[ -11 ]
c[ -10 ]
c[ -9 ]
c[ -8]
c[- 7 ]
c[ -4 ]
c[- 3 ]
c[ -2 ]
c[ -6 ]
c[ -5 ]
c[ -12 ]
43
Creating Sequences• Creations
– Strings• Use quotes• string1 = ""
– Lists• Use brackets• Separate multiple items with a comma• list1 = []
– Tuples• Use parenthesis• Separate multiple items with a comma• tuple = ()
44
Using Lists and Tuples• Differences
– Tuples and lists can both contain the same data– For practical purposes though each is used to hold
different types of items
45
Using Lists• Lists
– Not restricted to values of the same type• Programmers use lists to hold data that is of the same
type
– The length is not usually predetermined and can vary throughout the program
– Accessing elements out of range• Python exits and an out of range error is displayed
46
Using Tuples• Tuples
– Used to contain data that is related but not necessarily of the same type
• Each data item represents a unique piece of the overall portion
– In this case tuples are usually not iterated though– The needed data is accessed before hand
• A person’s name, age and birth date• Again this is not required but is a general rule
47
Sequence Unpacking• Unpacking
– A useful shortcut for to assign values to multiple variables in one statement
Sequence Slicing• Slicing
– Allows a programmer to access a portion of a string or element at once
– theSequence [ start:end ]– Returns the portion of the sequence from the
starting position up to the ending position
48
1 1 # Fig. 5.7: fig05_07.py# Fig. 5.7: fig05_07.py
2 2 # Unpacking sequences.# Unpacking sequences.
3 3 # create sequences# create sequences
55 aString = aString = "abc""abc"
6 6 aList = [aList = [ 1 1,, 2 2,, 3 3 ] ]
7 7 aTuple = aTuple = "a""a", , "A""A",, 1 1
9 9 # unpack sequences to variables# unpack sequences to variables
10 10 printprint "Unpacking string...""Unpacking string..."
1111 first, second, third = aStringfirst, second, third = aString
12 12 printprint "String values:""String values:", first, second, third, first, second, third
14 14 printprint "\nUnpacking list...""\nUnpacking list..."
1515 first, second, third = aListfirst, second, third = aList
16 16 printprint "List values:""List values:", first, second, third, first, second, third
17 17
18 18 printprint "\nUnpacking tuple...""\nUnpacking tuple..."
1919 first, second, third = aTuplefirst, second, third = aTuple
20 20 printprint "Tuple values:""Tuple values:", first, second, third, first, second, third
21 21
22 22 # swapping two values# swapping two values
23 23 x =x = 3 3
24 24 y =y = 4 4
25 25
26 26 printprint "\nBefore swapping: x = %d, y = %d""\nBefore swapping: x = %d, y = %d" % ( x, y ) % ( x, y )
2727 x, y = y, x x, y = y, x # swap variables# swap variables
28 28 printprint "After swapping: x = %d, y = %d""After swapping: x = %d, y = %d" % ( x, y ) % ( x, y )
Unpacking string...String values: a b c Unpacking list...List values: 1 2 3 Unpacking tuple...Tuple values: a A 1 Before swapping: x = 3, y = 4After swapping: x = 4, y = 3
49
1 1 # Fig. 5.8: fig05_08.py# Fig. 5.8: fig05_08.py
2 2 # Slicing sequences.# Slicing sequences.
4 4 # create sequences# create sequences
55 sliceString = sliceString = "abcdefghij""abcdefghij"
6 6 sliceTuple = (sliceTuple = ( 1 1,, 2 2,, 3 3,, 4 4,, 5 5,, 6 6,, 7 7,, 8 8,, 9 9,, 10 10 ) )
7 7 sliceList = [ sliceList = [ "I""I", , "II""II", , "III""III", , "IV""IV", , "V""V", , "VI""VI", , "VII""VII", , "VIII""VIII", , "IX""IX", , "X""X" ] ]
10 10 # print strings# print strings
11 11 printprint "sliceString: ""sliceString: ", sliceString, sliceString
12 12 printprint "sliceTuple: ""sliceTuple: ", sliceTuple, sliceTuple
13 13 printprint "sliceList: ""sliceList: ", sliceList, sliceList
14 14 printprint
16 16 # get slices# get slices
1717 start = int( raw_input( start = int( raw_input( "Enter start: ""Enter start: " ) ) ) )
18 18 end = int( raw_input( end = int( raw_input( "Enter end: ""Enter end: " ) ) ) )
20 20 # print slices# print slices
21 21 printprint "\nsliceString[""\nsliceString[", start, , start, ":"":", end, , end, "] = ""] = ", sliceString[ start:end ], sliceString[ start:end ]
24 24 printprint "sliceTuple[""sliceTuple[", start, , start, ":"":", end, , end, "] = ""] = ", sliceTuple[ start:end ], sliceTuple[ start:end ]
27 27 printprint "sliceList[""sliceList[", start, , start, ":"":", end, , end, "] = ""] = ", sliceList[ start:end ], sliceList[ start:end ]
sliceString: abcdefghijsliceTuple: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)sliceList: ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'] Enter start: -4Enter end: -1 sliceString[ -4 : -1 ] = ghisliceTuple[ -4 : -1 ] = (7, 8, 9)sliceList[ -4 : -1 ] = ['VII', 'VIII', 'IX']
50
Dictionaries• Dictionaries
– Mapping constructs consisting of key-value pairs• Referred to as hashes in other languages
– Unordered collection of references– Each value is referenced though key in the pair– Curley braces ({}) are used to create a dictionary– When entering values
• Use { key1:value1, … }
– Keys must be immutable values such as strings, numbers and tuples
– Values can be of any Python data type
51
List and Dictionary MethodsMethod Purpose
append( item ) Inserts item at the end of the list.
count( element ) Returns the number of occurrences of element in the list.
extend( newList ) Inserts the elements of newList at the end of the list.
index( element ) Returns the index of the first occurrence of element in the list. If element is not in the list, a ValueError exception occurs. [Note: We discuss exceptions in Chapter 12, Exception Handling.]
insert( index, item )
Inserts item at position index.
pop( [index] ) Parameter index is optional. If this method is called without arguments, it removes and returns the last element in the list. If parameter index is specified, this method removes and returns the element at position index.
remove( element ) Removes the first occurrence of element from the list. If element is not in the list, a ValueError exception occurs.
reverse() Reverses the contents of the list in place (rather than creating a reversed copy).
sort( [compare-function] )
Sorts the content of the list in place. The optional parameter
compare-function is a function that specifies the compare
criteria. The compare-function takes any two elements of the list (x and y) and returns -1 if x should appear before y, 0 if the orders of x and y do not matter and 1 if x should appear after
y. [Note: We discuss sorting in Section 5.9.] Fig. 5.12 List methods.
52
List and Dictionary Methods
Method Description
clear() Deletes all items from the dictionary.
copy() Creates and returns a shallow copy of the dictionary (the elements in the new dictionary are references to the elements in the original dictionary).
get( key [, returnValue] ) Returns the value associated with key. If key is not in the
dictionary and if returnValue is specified, returns
the specified value. If returnValue is not specified,
returns None.
has_key( key ) Returns 1 if key is in the dictionary; returns 0 if key is
not in the dictionary.
items() Returns a list of tuples that are key-value pairs.
keys() Returns a list of keys in the dictionary.
popitem() Removes and returns an arbitrary key-value pair as a tuple of two elements. If dictionary is empty, a Key-Error exception occurs. [Note: We discuss
exceptions in Chapter 12, Exception Handling.] This method is useful for accessing an element (i.e., print the key-value pair) before removing it from the dictionary.
53
List and Dictionary Methods
setdefault( key [, dummyValue] )
Behaves similarly to method get. If key is not in the dictionary and dummyValue is specified, inserts the key and the specified value into dictionary. If
dummyValue is not specified, value is None.
update( newDictionary ) Adds all key-value pairs from newDictionary to the current dictionary and overrides the values for keys that already exist.
values() Returns a list of values in the dictionary.
iterkeys() Returns an iterator of dictionary keys. [Note: We discuss iterators in Appendix O, Additional Python 2.2 Features.]
iteritems() Returns an iterator of key-value pairs. [Note: We discuss iterators in Appendix O, Additional Python 2.2 Features.]
itervalues() Returns an iterator of dictionary values. [Note: We discuss iterators in Appendix O, Additional Python 2.2 Features.]
Fig. 5.14 Dictionary methods.