Python
Csc 667/867
Course note credit to PrenticeHall
Printing a Line of Text
• Python Online Tutorial
http://www.python.org/doc/current/tut/
• Python Reference Manual
http://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
2
Adding Integers
• Functions
– The raw_input function
• Used to retrieve data from the user
– The int function
• Used to convert strings to integers
3
1
2
3
4
5
6
7
8
9
10
11
12
13
# Fig. 2.7: fig02_07.py
# Simple addition program.
# prompt user for input
integer1 = raw_input( "Enter first integer:\n" ) # read string
integer1 = int( integer1 ) # convert string to integer
integer2 = raw_input( "Enter second integer:\n" ) # read string
integer2 = int( integer2 ) # convert string to integer
sum = integer1 + integer2
print "Sum is", sum
# compute and assign sum
# print sum
Enter first integer:
45
Enter second integer:
72
Sum is 117
4
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).
5
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)
6
Arithmetic
O p e ra t o r( s)
O p e ra t io n ( s)
O rd e r o f Ev a lu a t io n ( Pre c e d e n c e )
( )
P arentheses
E valuated first. If the parentheses are nested, the
expression in the innerm ost pair is evaluated first. If
there are several pairs of parentheses “on the sam e
level” (i.e., not n ested), they are evaluated left to
right.
**
E xponentiation
E valuated second. If there are several, the y are
evaluated right to left.
* / // %
M ultiplication
D ivision
M odulus
E valuated third. If there are several, they are
A ddition
Subtraction
E valuated last. If there are several, the y are evaluated
left to right.
+ -
Fig . 2 .1 6 Pre c e d e n c e
evaluated left to right. [ N ote: T he
//
operator is
new in version 2.2]
o f a rit h m e t ic o p e ra t o rs.
7
Augmented Assignment
Symbols
A ssig n m e n t
sy m b o l
Sa m p le
e xp re ssio n
Exp la n a t io n
A ssig n s
+=
-=
*=
c += 7
d -= 4
e *= 5
c = c + 7
d = d - 4
e = e * 5
1 0 to c
**=
/=
%=
f **= 3
g /= 3
h %= 9
f = f ** 3
g = g / 3
h = h % 9
8
A ssu m e : c = 3 ,
d = 5, e = 4,
f = 2, g = 6,
h = 12
Fig . 3 .1 6 A u g m e n t e d
1 to d
2 0 to e
to
f
2 to g
3 to h
a rit h m e t ic a ssig n m e n t sy m b o ls.
8
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
9
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
10
1
2
3
4
5
6
7
8
9
10
# Fig. 2.18: fig02_18.py
# Creating strings and using quote characters in strings.
print "This is a string with \"double quotes.\""
print 'This is another string with "double quotes."'
print 'This is a string with \'single quotes.\''
print "This is another string with 'single quotes.'"
print """This string has "double quotes" and 'single quotes'.
You can even do multiple lines."""
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.
11
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# String formatting.
integerValue = 4237
print "Integer ", integerValue
print "Decimal integer %d" % integerValue
print "Hexadecimal integer %x\n" % integerValue
floatValue = 123456.789
print "Float", floatValue
print "Default float %f" % floatValue
print "Default exponential %e\n" % floatValue
print "Right justify integer (%8d)" % integerValue
print "Left justify integer (%-8d)\n" % integerValue
stringValue = "String formatting"
print "Force eight digits in integer %.8d" % integerValue
print "Five digits after decimal in float %.5f" % floatValue
print "Fifteen and five characters allowed in string:"
print "(%.15s) (%.5s)" % ( stringValue, stringValue )
12
Integer
4237
Decimal integer 4237
Hexadecimal integer 108d
Float 123456.789
Default float 123456.789000
Default exponential 1.234568e+005
Right justify integer (
Left justify \integer
4237)
(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)
13
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
14
Lines
• Logical Lines
(http://docs.python.org/ref/logical.html)
• Physical Lines
• Explicit 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
• Implicit Line Joining
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
15
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
16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Control Statement examples
# Class average program with counter-controlled repetition.
# initialization phase
total = 0
# sum of grades
gradeCounter = 1 # number of grades entered
# processing phase
while gradeCounter <= 10:
# loop 10 times
grade = raw_input( "Enter grade: " ) # get one grade
grade = int( grade ) # convert string to an integer
total = total + grade
gradeCounter = gradeCounter + 1
# termination phase
average = total / 10
# integer division
print "Class average is", average
17
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# More control statement example
# Class average program with sentinel-controlled repetition.
# initialization phase
total = 0
# sum of grades
gradeCounter = 0 # number of grades entered
# processing phase
grade = raw_input( "Enter grade, -1 to end: " ) # get one grade
grade = int( grade ) # convert string to an integer
while grade != -1:
total = total + grade
gradeCounter = gradeCounter + 1
grade = raw_input( "Enter grade, -1 to end: " )
grade = int( grade )
# termination phase
if gradeCounter != 0:
average = float( total ) / gradeCounter
print "Class average is", average
else:
print "No grades were entered"
18
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
19
1
2
3
4
5
6
7
8
9
10
11
# Fig. 3.24: fig03_24.py
# Using the break statement in a for structure.
for x in range( 1, 11 ):
if x == 5:
break
print x,
print "\nBroke out of loop at x =", x
1 2 3 4
Broke out of loop at x = 5
20
Logical Operators
Python 2.2b2 (#26, Nov 16
Type "help", "copyright",
>>> if 0:
...
print "0 is true"
... else:
...
print "0 is false"
...
0 is false
>>> if 1:
...
print "non-zero is
...
non-zero is true
>>> if -1:
...
print "non-zero is
...
non-zero is true
>>> print 2 < 3
1
>>> print 0 and 1
0
>>> print 1 and 3
3
2001, 11:44:11) [MSC 32 bit (Intel)] on win32
"credits" or "license" for more information.
true"
true"
Fig. 3.28 Truth values.
21
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
22
Using Lists
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.
>>> 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.
23
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Fig. 5.5: fig05_05.py
# Creating a histogram from a list of values.
values = [] # a list of values
# input 10 values from user
print "Enter 10 integers:"
for i in range( 10 ):
newValue = int( raw_input( "Enter integer %d: " % ( i + 1 ) ) )
values += [ newValue ]
# create histogram
print "\nCreating a histogram from values:"
print "%s %10s %10s" % ( "Element", "Value", "Histogram" )
for i in range( len( values ) ):
print "%7d %10d %s" % ( i, values[ i ], "*" * values[ i ] )
24
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
10 integers:
integer 1: 19
integer 2: 3
integer 3: 15
integer 4: 7
integer 5: 11
integer 6: 9
integer 7: 13
integer 8: 5
integer 9: 17
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 *
Fig05_05.py
Program Output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Fig. 5.6: fig05_06.py
# Creating and accessing tuples.
# retrieve hour, minute and second from user
hour = int( raw_input( "Enter hour: " ) )
minute = int( raw_input( "Enter minute: " ) )
second = int( raw_input( "Enter second: " ) )
currentTime = hour, minute, second # create tuple
print "The value of currentTime is:", currentTime
# access tuple
print "The number of seconds since midnight is", \
( currentTime[ 0 ] * 3600 + currentTime[ 1 ] * 60 +
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
26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Fig. 5.09: fig05_09.py
# Creating, accessing and modifying a dictionary.
# create and print an empty dictionary
emptyDictionary = {}
print "The value of emptyDictionary is:", emptyDictionary
# create and print a dictionary with initial values
grades = { "John": 87, "Steve": 76, "Laura": 92, "Edwin": 89 }
print "\nAll grades:", grades
# access and modify an existing dictionary
print "\nSteve's current grade:", grades[ "Steve" ]
grades[ "Steve" ] = 90
print "Steve's new grade:", grades[ "Steve" ]
# add to an existing dictionary
grades[ "Michael" ] = 93
print "\nDictionary grades after modification:"
print grades
# delete entry from dictionary
del grades[ "John" ]
print "\nDictionary grades after deletion:"
print grades
27
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}
28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Fig. 5.17: fig05_17.py
# Sorting a list.
aList = [ 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 ]
print "Data items in original order"
for item in aList:
print item,
aList.sort()
print "\n\nData items after sorting"
for item in aList:
print item,
print
Data items in original order
2 6 4 8 10 12 89 68 45 37
Data items after sorting
2 4 6 8 10 12 37 45 68 89
29
List and Dictionary Methods
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.
>>> 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 )
>>> 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]}
# make a deep copy
Fig. 5.15 Difference between a shallow copy and a deep copy.
30
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
>>> 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)
# 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
31
Fibo.py
CGI module
http://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"]
32
1
2
3
4
6
7
8
9
12
14
15
16
19
21
23
24
25
26
27
28
30
31
32
33
34
35
#!c:\Python\python.exe
# Fig. 6.5: fig06_05.py
# Program displaying CGI environment variables.
import os
import cgi
def printHeader( title ):
print """Content-type: text/html <?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head><title>%s</title></head><body>""" % title
rowNumber = 0
backgroundColor = "white"
printHeader( "Environment Variables" )
Function cgi.escape
print """<table style = "border: 0">"""
takes
a string and returns a properly
# print table of cgi variables and values
for item in os.environ.keys():
formatted XHMTL string
rowNumber += 1
if rowNumber % 2 == 0:
# even row numbers are white
backgroundColor = "white"
else:
# odd row numbers are grey
backgroundColor = "lightgrey"
print """<tr style = "background-color: %s"> <td>%s</td><td>%s</td>
</tr>""" % ( backgroundColor,cgi.escape( item ), cgi.escape(os.environ[ item ]))
39 print """</table></body></html>"""
33
fig06_05.py
34
1
2
6
7
8
9
10
11
13
15
17
19
20
21
22
23
24
25
26
27
28
30
31
32
33
34
35
37
38
40
#!c:\Python\python.exe
import os
import cgi
def printHeader( title ):
print """Content-type: text/html
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN“ "DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml"> <head><title>%s</title></head>
<body>""" % title
printHeader( "QUERY_STRING example" )
print "<h1>Name/Value Pairs</h1>"
query = os.environ[ "QUERY_STRING" ]
if len( query ) == 0:
print """<p><br />
Please add some name-value pairs to the URL above.
Or try <a href = "fig06_06.py?name=Veronica&amp;age=23">this</a>.
</p>"""
else:
print """<p style = "font-style: italic">
The query string is '%s'.</p>""" % cgi.escape( query )
pairs = cgi.parse_qs( query )
for key, value in pairs.items():
print "<p>You set '%s' to value %s</p>"" % \
( key, value )
print "</body></html>"
35
36
1
2
6
7
8
9
10
12
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!c:\Python\python.exe
import cgi
def printHeader( title ):
print """Content-type: text/html
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head><title>%s</title></head>
<body>""" % title
printHeader( "Using 'post' with forms" )
print """<p>Enter one of your favorite words here:<br /></p>
<form method = "post" action = "fig06_09.py">
<p>
<input type = "text" name = "word" />
<input type = "submit" value = "Submit word" />
</p>
</form>"""
pairs = cgi.parse()
if pairs.has_key( "word" ):
print """<p>Your word is:
<span style = "font-weight: bold">%s</span></p>""" \
% cgi.escape( pairs[ "word" ][ 0 ] )
print "</body></html>"
37
38
Cookie
• http://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/cgi667/cookiecounter.py
39
Check http://docs.python.org/lib/module-Cookie.html
for detail information for cgi module
#!/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
40
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
41
Sequences
Name sequence (c)
Position number of the
element within sequence
c
Fig. 5.1
c[ 0 ]
-45
c[ -12 ]
c[ 1 ]
6
c[ -11 ]
c[ 2 ]
0
c[ -10 ]
c[ 3 ]
72
c[ -9 ]
c[ 4 ]
1543
c[ -8]
c[ 5 ]
-89
c[- 7 ]
c[ 6 ]
0
c[ -6 ]
c[ 7 ]
62
c[ -5 ]
c[ 8]
-3
c[ -4 ]
c[ 9 ]
1
c[- 3 ]
c[ 10 ]
6453
c[ -2 ]
c[ 11 ]
-78
c[ -1 ]
Sequence with elements and indices.
42
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 = ()
43
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
44
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
45
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
46
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
47
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 = 4
After swapping: x = 4, y = 3
1
2
3
5
6
7
9
10
11
12
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Fig. 5.7: fig05_07.py
# Unpacking sequences.
# create sequences
aString = "abc"
aList = [ 1, 2, 3 ]
aTuple = "a", "A", 1
# unpack sequences to variables
print "Unpacking string..."
first, second, third = aString
print "String values:", first, second, third
print "\nUnpacking list..."
first, second, third = aList
print "List values:", first, second, third
print "\nUnpacking tuple..."
first, second, third = aTuple
print "Tuple values:", first, second, third
# swapping two values
x=3
y=4
print "\nBefore swapping: x = %d, y = %d" % ( x, y )
x, y = y, x # swap variables
print "After swapping: x = %d, y = %d" % ( x, y )
48
1
2
4
5
6
7
10
11
12
13
14
16
17
18
20
21
24
27
# Fig. 5.8: fig05_08.py
# Slicing sequences.
# create sequences
sliceString = "abcdefghij"
sliceTuple = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 )
sliceList = [ "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X" ]
# print strings
print "sliceString: ", sliceString
print "sliceTuple: ", sliceTuple
print "sliceList: ", sliceList
print
# get slices
start = int( raw_input( "Enter start: " ) )
end = int( raw_input( "Enter end: " ) )
# print slices
print "\nsliceString[", start, ":", end, "] = ", sliceString[ start:end ]
print "sliceTuple[", start, ":", end, "] = ", sliceTuple[ start:end ]
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']
49
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
50
List and Dictionary Methods
M e th o d
Pu rp o se
a p p e n d ( item )
Inserts item at the end of the list.
c o u n t ( elem en t )
R eturns the num be r of occurre nces of elem ent in the list.
e x t e n d ( n ew L ist )
Inserts the ele m e nts o f new L ist at the end of the list.
i n d e x ( elem en t )
R eturns the inde x o f the first occurre nce of elem ent in the list. If
ele m e nt is not in the list, a
ValueError
exceptio n occurs.
[N ote: W e discuss exceptio ns in C hapter 12 , E xceptio n
H a nd ling .]
i n s e r t ( in d ex , item
)
Inserts item at positio n index.
p o p ( [in d ex ] )
P ara m eter index is optio na l. If this m ethod is called w itho ut
argum e nts, it re m o ves and returns the last ele m e nt in the list. If
para m eter index is specified, this m ethod re m o ves and returns
the ele m e nt at positio n index.
r e m o v e ( elem en t )
R e m o ves the first occurre nce of elem ent fro m the list. If elem ent
is not in the list, a
ValueError
exce ptio n occurs.
reverse()
R everses the contents of the list in place (ra ther tha n creating a
reversed copy).
s o r t ( [co m p a refu n ctio n ] )
S orts the conte nt o f the list in p lace. T h e optio na l para m eter
co m p a re-fu n ctio n is a functio n that specifies the co m pare
criteria. T he co m p a re-fu n ctio n takes any tw o ele m e nts of
the list (x and y) and returns -1 if x sho uld appear before y, 0 if
the orders of x and y do no t m atter and 1 if x sho uld appear after
y. [ N o te : W e discuss sorting in S ectio n 5.9.]
Fig . 5 .1 2 List
m e t h o d s.
51
List and Dictionary Methods
M e th o d
D e sc rip t io n
clear()
D e le te s a ll ite m s fro m th e d ic tio na ry.
copy()
C re a te s an d re tu rn s a sh a llo w c op y o f th e d ic tio n ary (th e
e le m e n ts in the ne w d ic tion a ry a re re fe re n c e s to th e
e le m e n ts in the o rigin a l d ic tio n a ry).
g e t ( k ey [, retu rn V a lu e] )
R e tu rn s the va lu e a ssoc ia te d w ith ke y . If k e y is not in th e
retu rn V a lu e is sp e c ifie d , re tu rn s
th e spe c ifie d va lu e . If retu rn V a lu e is n o t sp e cifie d ,
re tu rn s N o n e .
d ic tio n a ry a n d if
h a s _ k e y ( k ey )
R e tu rn s
1
if k e y is in th e d ic tio n a ry; re tu rn s
0
if k e y is
n o t in th e d ic tio n a ry.
items()
R e tu rn s a list o f tu p le s tha t a re ke y-va lu e p a irs.
keys()
R e tu rn s a list o f ke ys in th e d ic tion a ry.
popitem()
R e m o ve s an d re tu rn s a n a rb itra ry ke y-va lu e p a ir as a
tu p le o f tw o e le m en ts. If d ic tio n a ry is e m p ty, a
Error
Key-
e xc ep tio n o c cu rs. [N o te : W e d isc u ss
e xc e p tio n s in C ha p te r 1 2, E xc e p tion H an d lin g.] T h is
m e th od is use fu l fo r a c c e ssin g a n e le m en t (i.e ., p rin t th e
ke y-va lu e p a ir) b e fo re rem o vin g it fro m th e d ic tion a ry .
52
List and Dictionary Methods
setdefault(
d u m m y V a lu e ] )
ke y [,
B e h a ve s sim ila rly to m e th od
g e t . If ke y
is n o t in th e
d ic tio n a ry a n d d u m m y V a lu e is spe c ifie d , in se rts th e ke y
a n d th e sp e c ifie d va lu e in to d ic tio n a ry. If
d u m m yV a lu e
is n o t sp ec ifie d , va lu e is
None.
u p d a t e ( n ew D ictio n a ry )
A d d s a ll ke y- va lu e p a irs fro m ne wD ic tio n a ry to th e
c u rre n t d ic tion a ry a n d o ve rride s th e va lu e s fo r keys th a t
a lre a d y e x ist.
values()
R e tu rn s a list o f va lu e s in the d ic tio n a ry.
iterkeys()
R e tu rn s a n ite ra to r o f d ic tio na ry ke ys. [ N o te : W e
d isc u ss ite ra to rs in A p p e nd ix O , A d d itio n a l P yth o n 2 .2
Fe a tu re s.]
iteritems()
R e tu rn s a n ite ra to r o f ke y-va lu e p a irs. [ N o te : W e
d isc u ss ite ra to rs in A p p e nd ix O , A d d itio n a l P yth o n 2 .2
Fe a tu re s.]
itervalues()
R e tu rn s a n ite ra to r o f d ic tio na ry va lu e s. [ N o te : W e
d isc u ss ite ra to rs in A p p e nd ix O , A d d itio n a l P yth o n 2 .2
Fe a tu re s.]
Fig . 5 .1 4 D ic t io n a ry
m e t h o d s.
53
Descargar

Chapter 4 – Control Structures Part 1