PythonPython Csc 667/867 Course note credit to PrenticeHall
2 Printing a Line of Text Python Online Tutorial Python Reference Manual 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 # Fig. 2.7: fig02_07.py 2 # Simple addition program. 3 4 # prompt user for input 5 integer1 = raw_input( "Enter first integer:\n" ) # read string 6 integer1 = int( integer1 ) # convert string to integer 7 8 integer2 = raw_input( "Enter second integer:\n" ) # read string 9 integer2 = int( integer2 ) # convert string to integer sum = integer1 + integer2 # compute and assign sum print "Sum is", sum # print sum Enter first integer: 45 Enter second integer: 72 Sum is 117
5 Another Program: Adding Integers Python 2.2b2 (#26, Nov , 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.8Adding 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
8 Augmented 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 # Fig. 2.18: fig02_18.py 2 # Creating strings and using quote characters in strings. 3 4 print "This is a string with \"double quotes.\"" 5 print 'This is another string with "double quotes."' 6 print 'This is a string with \'single quotes.\'' 7 print "This is another string with 'single quotes.'" 8 print """This string has "double quotes" and 'single quotes'. 9 You can even do multiple lines.""" 10 print '''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 # String formatting. 3 4 integerValue = print "Integer ", integerValue 6 print "Decimal integer %d" % integerValue 7 print "Hexadecimal integer %x\n" % integerValue 8 9 floatValue = print "Float", floatValue 11 print "Default float %f" % floatValue 12 print "Default exponential %e\n" % floatValue print "Right justify integer (%8d)" % integerValue 15 print "Left justify integer (%-8d)\n" % integerValue stringValue = "String formatting" 18 print "Force eight digits in integer %.8d" % integerValue 19 print "Five digits after decimal in float %.5f" % floatValue 20 print "Fifteen and five characters allowed in string:" 21 print "(%.15s) (%.5s)" % ( stringValue, stringValue )
13 Integer 4237 Decimal integer 4237 Hexadecimal integer 108d Float Default float Default exponential e+005 Right justify integer ( 4237) Left justify \integer (4237 ) Force eight digits in integer Five digits after decimal in float 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 ( 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 1# Control Statement examples 2# Class average program with counter-controlled repetition. 3 4# initialization phase 5total = 0 # sum of grades 6gradeCounter = 1 # number of grades entered 7 8# processing phase 9while gradeCounter <= 10: # loop 10 times 10 grade = raw_input( "Enter grade: " ) # get one grade 11 grade = int( grade ) # convert string to an integer 12 total = total + grade 13 gradeCounter = gradeCounter # termination phase 16average = total / 10 # integer division 17print "Class average is", average
18 1# More control statement example 2# Class average program with sentinel-controlled repetition. 3 4# initialization phase 5total = 0 # sum of grades 6gradeCounter = 0 # number of grades entered 7 8# processing phase 9grade = raw_input( "Enter grade, -1 to end: " ) # get one grade 10grade = int( grade ) # convert string to an integer 11 12while grade != -1: 13 total = total + grade 14 gradeCounter = gradeCounter grade = raw_input( "Enter grade, -1 to end: " ) 16 grade = int( grade ) 17 18# termination phase 19if gradeCounter != 0: 20 average = float( total ) / gradeCounter 21 print "Class average is", average 22else: 23 print "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 # Fig. 3.24: fig03_24.py 2 # Using the break statement in a for structure. 3 4 for x in range( 1, 11 ): 5 6 if x == 5: 7 break 8 9 print x, print "\nBroke out of loop at x =", x Broke out of loop at x = 5
21 Logical Operators Python 2.2b2 (#26, Nov , 11:44:11) [MSC 32 bit (Intel)] on win32 Type "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 < 3 1 >>> print 0 and 1 0 >>> print 1 and 3 3 Fig. 3.28Truth values.
22 Variable Scope def demo (f_in): global somevar # shared with main code demo.tom = 16 # An attribute accessible from main code somevar += 1 f_in = 2 demo.another = 12 # A local variable, independent of main code another = 13 res = f_in+14 # Value passed in (f_in) return res somevar = 27 # accessed in function via global another = 17 # not accessed in function pval = 16 # accessed in function via parameter print demo(pval) print pval print demo.tom # function attribute print somevar print another print demo.another
23 Using Lists Python 2.2b2 (#26, Nov , 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> aList = [ 1 ] >>> print aList[ 13 ] Traceback (most recent call last): File " ", line 1, in ? IndexError: list index out of range Fig. 5.4Out-of-range error.
24 1 # Fig. 5.5: fig05_05.py 2 # Creating a histogram from a list of values. 3 4 values = [] # a list of values 5 6 # input 10 values from user 7 print "Enter 10 integers:" 8 9 for i in range( 10 ): 10 newValue = int( raw_input( "Enter integer %d: " % ( i + 1 ) ) ) 11 values += [ newValue ] # create histogram 14 print "\nCreating a histogram from values:" 15 print "%s %10s %10s" % ( "Element", "Value", "Histogram" ) for i in range( len( values ) ): 18 print "%7d %10d %s" % ( i, values[ i ], "*" * values[ i ] )
Fig05_05.py Program Output Enter 10 integers: Enter integer 1: 19 Enter integer 2: 3 Enter integer 3: 15 Enter integer 4: 7 Enter integer 5: 11 Enter integer 6: 9 Enter integer 7: 13 Enter integer 8: 5 Enter integer 9: 17 Enter 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 # Fig. 5.6: fig05_06.py 2 # Creating and accessing tuples. 3 4 # retrieve hour, minute and second from user 5 hour = int( raw_input( "Enter hour: " ) ) 6 minute = int( raw_input( "Enter minute: " ) ) 7 second = int( raw_input( "Enter second: " ) ) 8 9 currentTime = hour, minute, second # create tuple print "The value of currentTime is:", currentTime # access tuple 14 print "The number of seconds since midnight is", \ 15 ( currentTime[ 0 ] * currentTime[ 1 ] * currentTime[ 2 ] ) Enter hour: 9 Enter minute: 16 Enter second: 1 The value of currentTime is: (9, 16, 1) The number of seconds since midnight is 33361
27 1 # Fig. 5.09: fig05_09.py 2 # Creating, accessing and modifying a dictionary. 3 4 # create and print an empty dictionary 5 emptyDictionary = {} 6 print "The value of emptyDictionary is:", emptyDictionary 7 8 # create and print a dictionary with initial values 9 grades = { "John": 87, "Steve": 76, "Laura": 92, "Edwin": 89 } 10 print "\nAll grades:", grades # access and modify an existing dictionary 13 print "\nSteve's current grade:", grades[ "Steve" ] 14 grades[ "Steve" ] = print "Steve's new grade:", grades[ "Steve" ] # add to an existing dictionary 18 grades[ "Michael" ] = print "\nDictionary grades after modification:" 20 print grades # delete entry from dictionary 23 del grades[ "John" ] 24 print "\nDictionary grades after deletion:" 25 print grades
28 The value of emptyDictionary is: {} All grades: {'Edwin': 89, 'John': 87, 'Steve': 76, 'Laura': 92} Steve's current grade: 76 Steve'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 # Fig. 5.17: fig05_17.py 2 # Sorting a list. 3 4 aList = [ 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 ] 5 6 print "Data items in original order" 7 8 for item in aList: 9 print item, aList.sort() print "\n\nData items after sorting" for item in aList: 16 print item, print Data items in original order Data items after sorting
30 List and Dictionary Methods Python 2.2b2 (#26, Nov , 11:44:11) [MSC 32 bit (Intel)] on win32 Type "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.15Difference between a shallow copy and a deep copy.
31 Modules Check 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) >>> 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) >>> from fibo import fib, fib2 >>> fib(500)
32 CGI module form = cgi.FieldStorage() if not (form.has_key("name") and form.has_key("addr")): print " Error " print "Please fill in the name and addr fields." return print " name:", form["name"].value print " addr:", form["addr"].value … value = form.getlist("username") usernames = ",".join(value) … fileitem = form["userfile"]
33 1 #!c:\Python\python.exe 2 # Fig. 6.5: fig06_05.py 3 # Program displaying CGI environment variables. 4 import os 6 import cgi 7 8 def printHeader( title ): 9 print """Content-type: text/html 9 print """Content-type: text/html 12 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 14 "DTD/xhtml1-strict.dtd"> %s """ % title 19 rowNumber = 0 21 backgroundColor = "white" 23 printHeader( "Environment Variables" ) 24 print """ """ # print table of cgi variables and values 27 for item in os.environ.keys(): 28 rowNumber += 1 30 if rowNumber % 2 == 0: # even row numbers are white 31 backgroundColor = "white" 32 else: # odd row numbers are grey 33 backgroundColor = "lightgrey" 34print """ %s %s 34print """ %s %s 35 """ % ( backgroundColor,cgi.escape( item ), cgi.escape(os.environ[ item ])) 39 print """ """ Function cgi.escape takes a string and returns a properly formatted XHMTL string
34 fig06_05.py
35 1 #!c:\Python\python.exe 2 import os 6 import cgi 7 8 def printHeader( title ): 9 print """Content-type: text/html <!DOCTYPE html PUBLIC 13 "-//W3C//DTD XHTML 1.0 Strict//EN “ "DTD/xhtml1-strict.dtd"> 15 %s 15 %s 17 """ % title printHeader( "QUERY_STRING example" ) 21 print " Name/Value Pairs " query = os.environ[ "QUERY_STRING" ] if len( query ) == 0: 26 print """ 26 print """ 27 Please add some name-value pairs to the URL above. 28 Or try this. 30 """ 31 else: 32 print """ 32 print """ 33 The query string is '%s'. """ % cgi.escape( query ) 34 pairs = cgi.parse_qs( query ) 35 for key, value in pairs.items(): 37 print " You set '%s' to value %s "" % \ 38 ( key, value ) 40 print " "
36
37 1 #!c:\Python\python.exe 2 import cgi 6 7 def printHeader( title ): 8 print """Content-type: text/html 9 10 <!DOCTYPE html PUBLIC 12 "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> %s 15 %s """ % title printHeader( "Using 'post' with forms" ) 20 print """ Enter one of your favorite words here: 20 print """ Enter one of your favorite words here: """ pairs = cgi.parse() if pairs.has_key( "word" ): 31 print """ Your word is: 32 %s """ \ 33 % cgi.escape( pairs[ "word" ][ 0 ] ) print " "
38
39 Cookie c.htmlhttp://wp.netscape.com/newsref/std/cookie_spe c.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 SimpleCookie import cgi import 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 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.1Sequence with elements and indices c[ 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 # Fig. 5.7: fig05_07.py 2 # Unpacking sequences. 3 # create sequences 5 aString = "abc" 6 aList = [ 1, 2, 3 ] 7 aTuple = "a", "A", 1 9 # unpack sequences to variables 10 print "Unpacking string..." 11 first, second, third = aString 12 print "String values:", first, second, third 14 print "\nUnpacking list..." 15 first, second, third = aList 16 print "List values:", first, second, third print "\nUnpacking tuple..." 19 first, second, third = aTuple 20 print "Tuple values:", first, second, third # swapping two values 23 x = 3 24 y = print "\nBefore swapping: x = %d, y = %d" % ( x, y ) 27 x, y = y, x # swap variables 28 print "After swapping: x = %d, y = %d" % ( x, y ) Unpacking string... String values: a b c Unpacking list... List values: Unpacking tuple... Tuple values: a A 1 Before swapping: x = 3, y = 4 After swapping: x = 4, y = 3
49 1 # Fig. 5.8: fig05_08.py 2 # Slicing sequences. 4 # create sequences 5 sliceString = "abcdefghij" 6 sliceTuple = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ) 7 sliceList = [ "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X" ] 10 # print strings 11 print "sliceString: ", sliceString 12 print "sliceTuple: ", sliceTuple 13 print "sliceList: ", sliceList 14 print 16 # get slices 17 start = int( raw_input( "Enter start: " ) ) 18 end = int( raw_input( "Enter end: " ) ) 20 # print slices 21 print "\nsliceString[", start, ":", end, "] = ", sliceString[ start:end ] 24 print "sliceTuple[", start, ":", end, "] = ", sliceTuple[ start:end ] 27 print "sliceList[", start, ":", end, "] = ", sliceList[ start:end ] sliceString: abcdefghij sliceTuple: (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) sliceList: ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'] Enter start: -4 Enter end: -1 sliceString[ -4 : -1 ] = ghi sliceTuple[ -4 : -1 ] = (7, 8, 9) sliceList[ -4 : -1 ] = ['VII', 'VIII', 'IX']
50 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 Methods
52 List and Dictionary Methods
53 List and Dictionary Methods