january 24, 2006and now for something completely different 1 “and now for something completely...
TRANSCRIPT
January 24, 2006 And Now For Something Completely Different
1
“And Now For Something Completely Different”
A Quick Tutorial of the Python Programming Language
Michael Scherger
Department of Computer Science
Kent State University
January 24, 2006 And Now For Something Completely Different
2
Contents
• Python Resources
• Python Basics and Language Elements
• Statements and Control Structures
• Input, Output, and File Access
• Functions
• Classes and Objects
January 24, 2006 And Now For Something Completely Different
3
Python Resources
January 24, 2006 And Now For Something Completely Different
4
Python Resources
• Python Web Site: http://www.python.org
• Check out the tutorial at: http://www.python.org/doc/tut
• Download current stable version for your PC
January 24, 2006 And Now For Something Completely Different
5
Running Python
• PC– c:\>python – Use Python GUI called ‘IDLE’
• Linux• % python
• Mac version available
January 24, 2006 And Now For Something Completely Different
6
Running Python
January 24, 2006 And Now For Something Completely Different
7
Running Python
January 24, 2006 And Now For Something Completely Different
8
Python Basics and Language Elements
January 24, 2006 And Now For Something Completely Different
9
Numbers
• Integers– Decimal
• At least 32 bit
– Octal and hexadecimal
• Long integers– Limited by memory size– Trailing “L”
• Floating point• Complex
– Use “j” instead of “i”
• Boolean
>>> 1+12>>> 1+1.02.0>>> 1+1e02.0>>> >>> 999999999999999999999999999999L>>> 99999999999999999999999999999999999999999999999999999999L>>>9999999999999999999999999999999999999999999999999999999999999999999999999999999999L>>> >>> 1717>>> 02117>>> 0x1117>>>
January 24, 2006 And Now For Something Completely Different
10
Variables
• Variables do not have types
• You do not declare variables– They appear when you
assign them– They disappear when
you do not use them anymore
>>> x = 1 + 1>>> x2>>> x = 1 + 1.0>>> x2.0>>> >>> y
Traceback (most recent call last): File "<pyshell#20>", line 1, in -toplevel- yNameError: name 'y' is not defined>>> y = None>>> y>>> y == NoneTrue>>> del y>>> y
Traceback (most recent call last): File "<pyshell#25>", line 1, in -toplevel- yNameError: name 'y' is not defined>>>
January 24, 2006 And Now For Something Completely Different
11
Lists
• Python’s array like object is a list– Uses [ ]
– Subscripted like arrays in C (zero based)
– Mutable
– Use len(L) to get the length of the list
>>> z = [4, 5, 6]>>> z[1]5>>> z[1] = 7>>> z[4, 7, 6]>>> len( z )3>>>
January 24, 2006 And Now For Something Completely Different
12
Lists
• Indexing– Uses bracket notation– Indexes start at 0…can have a negative index
name = [“Cleese”, “John”] # example of strings in a list
print name[1], name[0] # prints “John Cleese”
name[0] = “Smith”
x=[[1,2,3],[y,z],[[[]]]] # example of lists in a list
“A” “B” “C” “D” “E”0 1 2 3 4
-5 -4 -3 -2 -1
January 24, 2006 And Now For Something Completely Different
13
Lists
• Slicing is similar to indexing except you indicate both the start and stop index separated by a colon
x = ["spam1","spam2","spam3","spam4","spam5","eggs","and","spam6"]
print x[5:7] # Prints the list ["eggs","and"]
“A” “B” “C” “D” “E”
0 1 2 3 4 5
-5 -4 -3 -2 -1
January 24, 2006 And Now For Something Completely Different
14
List Methods
• append() add an element to the end of the list
• pop() remove an element from the end of a list
• insert() add an element anywhere in the list
• + and * list concatenation and replication
• And a whole bunch more…look them up!
January 24, 2006 And Now For Something Completely Different
15
Strings• A string is a sequence of
characters between quotes; either “ “ or ‘ ‘
– There is no character data type in Python…only string
• Strings are not arrays of characters as in C/C++!
– Use subscript notation to read individual characters as a string
– Strings are immutable
– Use len(S) to get the length of the string
>>> x = "abc">>> x[0]'a'>>> len(x)3>>> x[0] = 'd'
Traceback (most recent call last):
File "<pyshell#34>", line 1, in -toplevel-
x[0] = 'd'TypeError: object doesn't
support item assignment>>>
January 24, 2006 And Now For Something Completely Different
16
Converting Values
• String values can be converted to integers using the int() function
• String values can be converted to floating points using the float() function
• Ints and floats can be converted to string values str() function
• Example
x = int( “10” )y = float( “10”)yy = float (10)Z = str(3.14159)
January 24, 2006 And Now For Something Completely Different
17
String Methodsupper() Returns the uppercase version of the string
lower() Returns the lowercase version of the string
swapcase() Returns a new string where the case of each letter is switched
capitalize() Returns a new string with the first letter capitalized and the remaining letters are in lowercase
title() Returns a new string with the first letter of each word capitalized and all other letters are in lower case
strip() Returns a new string with leading and trailing white space removed.
replace( old, new, [,max]) Returns a new string where occurrences of the string “old” are replaced by “new” up to “max” number of times
January 24, 2006 And Now For Something Completely Different
18
Tuples
• Tuples are like lists– Immutable
– Use ( ) notation instead of [ ]’s for creation
– Uses [ ] notation for indexing and slicing
>>> x = (1, "Mike", 2, Laurie", 3, "Sarah")
>>> x(1, 'Mike', 2, 'Laurie', 3, 'Sarah')>>> x[1] = 'Michael'
Traceback (most recent call last): File "<pyshell#46>", line 1, in -
toplevel- x[1] = 'Michael'TypeError: object doesn't support
item assignment>>>
January 24, 2006 And Now For Something Completely Different
19
Dictionaries
• Dictionaries are unordered lists– Associative array/list or table or map– List of “key/value” pairs– Use “key” to look up the element or value
person = {'first name': "Robin", 'last name’ : "Hood", 'occupation': "Scoundrel" }
person[‘last name’] = “of Locksley”
January 24, 2006 And Now For Something Completely Different
20
Dictionary Methods
• keys() returns a list of keys
• values() returns a list of values
• items() returns a list of key value pairs
• has_key() tests if a key exists
• And a whole bunch more…look them up!
January 24, 2006 And Now For Something Completely Different
21
Assignments
• Assignment uses =
• Equality uses ==
• Not Equal uses != or <>
x, y, z = 1, 2, 3
first, second = second, first
a = b = 123
January 24, 2006 And Now For Something Completely Different
22
Other Assignment Operators
• Augmented assignment operators– A combination of assignment and a mathematical
operation
• *= x *= 5 x = x * 5• /= x /= 5 x = x / 5• %= x %=5 x = x % 5• += x += 5 x = x + 5• -= x -= 5 x = x - 5
January 24, 2006 And Now For Something Completely Different
23
Logical Values
• Python 2.3 has a Boolean type– Prior versions do not
– False is zero or empty
– True is not False (non-zero or not empty)
– And, Or, Not are short-circuited
– Can do lexicographic comparison of sequences (lists, strings, tuples)
• 1 < 2 # True• 1 > 2 # False• [1,2] < [3,4] # True• [1,2] == [1,2] # True• “ab” == “a” + “b” # True• (1,2) == [1,2] # False• not [] # True• not [1,2,3] #
False• not ‘’ # True• not ‘ab’ # False
January 24, 2006 And Now For Something Completely Different
24
Statements and Control Structures
January 24, 2006 And Now For Something Completely Different
25
Blocks
• Blocks are indicated using indentation only– No BEGIN/END or { }
if x < 5 or (x > 10 and x < 20):print “The value is OK.”
if x < 5 or 10 < x < 20:print “The value is OK.”
January 24, 2006 And Now For Something Completely Different
26
If-Elif-Else
if color == Green:do_green_function()
elif color == Blue:do_blue_function()
elif color == Red:do_red_function()
else:report_error()
January 24, 2006 And Now For Something Completely Different
27
While Loops
• Example of a while loops
x = 10
while x >= 0:
print “x is still negative.”
x = x-1
January 24, 2006 And Now For Something Completely Different
28
For Loops
• To make an “ordinary” for loop use the built-in function range()
# Print out the values from 0
# to 99 inclusive
for value in range(100):
print value
January 24, 2006 And Now For Something Completely Different
29
For Loops• More examples of for loops
# print values in a listfor value in [1, 2, 3, 4, 5, 4, 3, 2, 1]:
print value
# print 10 thru 19for value in range(10,20):
print value
# print 10 12 14 16 18for value in range(10, 20, 2):
print value
January 24, 2006 And Now For Something Completely Different
30
Input, Output, and File Access
January 24, 2006 And Now For Something Completely Different
31
Getting User Input
• The raw_input function returns a string.– Be careful!
• 10 is not the same as “10”• Other functions convert strings to integers and vice
versa.
• Example: Personal Greeter
January 24, 2006 And Now For Something Completely Different
32
A Tiny Algorithm
• Prompt user for a number• Print out the square of the number
x = input( “Please enter a number: “)
print “The square of that number is”, x * x
• Could also use… x = raw_input( “Please enter a number: “)
x = int(x)
print “The square of that number is”, x * x
January 24, 2006 And Now For Something Completely Different
33
File Input / Output
• Example
filespec = open( “somefile”, “r” )
s = filespec.readline() # read one line
s = filespec.readlines() # read all lines
filespec.close()
January 24, 2006 And Now For Something Completely Different
34
File Input / Output
• Example
filespec = open( “somefile”, “w” )
filespec.writeline(s) # write one string
filespec.writelines(l) # write string list
filespec.close()
January 24, 2006 And Now For Something Completely Different
35
Functions
January 24, 2006 And Now For Something Completely Different
36
Functions
• Use the keyword def– Passing parameters– Named arguments– Default values– Variable scoping
def square(x):return x*x
print square(2) # prints out 4
January 24, 2006 And Now For Something Completely Different
37
Functions
• When you pass a parameter to a function, you bind the parameter to the value
• Creates a new reference
def change(some_list): some_list[1] = 4
x = [1,2,3] change(x) print x # Prints out [1,4,3]
January 24, 2006 And Now For Something Completely Different
38
Functions
• Another example
def nochange(x): x = 0
y = 1 nochange(y) print y # Prints out 1
• Example: Balanced Parentheses and Fibonocci Numbers
January 24, 2006 And Now For Something Completely Different
39
Functions
• Example
>>>def sumdif(a, b):return a+b, a-b
>>>sumdif( 5, 7 )(12,2)>>>
January 24, 2006 And Now For Something Completely Different
40
Putting It All Together
• Write a Python version of wc (word count)– Writes the counts of the number of characters, words,
and lines in a file
• Algorithm– open the file– count the characters, words, and lines– write out the counts– close the file
• Example: wc– % python wc.py somefile.ext
January 24, 2006 And Now For Something Completely Different
41
Classes and Objects
January 24, 2006 And Now For Something Completely Different
42
Classes and Objects
class Basket:def __init__(self, contents=None):self.contents = contents or []
def add(self, element):self.contents.append(element)
def print_me(self):result = “”for element in self.contents:
result = result + “ “ + `element`print “Contains: “ + result
January 24, 2006 And Now For Something Completely Different
43
Classes and Objects• All methods (functions in an object) received an additional argument at the
start of the argument list containing the object itself. (Called self which is customary)
• Methods are called like this: object.method( arg1, arg2)
• Some method names, like __init__ (two underscores on each side), are predefined and mean special things (constructor)
• Some arguments are optional and given and default value
• Short circuit evaluation and assignment
• Backquotes convert an object to its string representation
• Addition sign (+) is used for string concatenation
January 24, 2006 And Now For Something Completely Different
44
Classes and Objects
• Instead of short circuit to assign contents…could have written the statement like this
if contents:self.contents = contents
else:self.contents = []
def __init__(self,contents=[])self.contents = contents[:]
January 24, 2006 And Now For Something Completely Different
45
Classes and Objects
• To create an instance of a class (object)
a = Basket()
b = Basket( [“apple”, “lemon”])
b.add( “orange” )
b.print_me()
January 24, 2006 And Now For Something Completely Different
46
Classes and Objects
• Convert object to string– Use the __str__ method
def __str__(self)
result = “”
for element in self.contents:result = result + “ “ + `element`
return “Contains: “ + “ “ + result
January 24, 2006 And Now For Something Completely Different
47
Classes and Objects• Example: Basket Class
• >>> b = Basket()• >>> b• <__main__.Basket instance at 0x00A09B98>• >>> print b• Contains:• >>> b.add( "Foo" )• >>> print b• Contains: 'Foo'• >>> b.add (["Foo", "Bar"])• >>> b.print_me()• Contains: 'Foo' ['Foo', 'Bar']• >>> b.add ((1,2,3))• >>> print b• Contains: 'Foo' ['Foo', 'Bar'] (1, 2, 3)• >>>