Download And Now For Something Completely Different

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
“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
1
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
2
Python Resources
January 24, 2006
And Now For Something
Completely Different
3
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
4
Running Python
• PC
– c:\>python
– Use Python GUI called ‘IDLE’
• Linux
• % python
• Mac version available
January 24, 2006
And Now For Something
Completely Different
5
Running Python
January 24, 2006
And Now For Something
Completely Different
6
Running Python
January 24, 2006
And Now For Something
Completely Different
7
Python Basics and Language
Elements
January 24, 2006
And Now For Something
Completely Different
8
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
January 24, 2006
>>> 1+1
2
>>> 1+1.0
2.0
>>> 1+1e0
2.0
>>>
>>> 999999999999999
999999999999999L
>>> 9999999999999999999999999999
9999999999999999999999999999L
>>>99999999999999999999999999999999999999999
99999999999999999999999999999999999999999L
>>>
>>> 17
17
>>> 021
17
>>> 0x11
17
>>>
And Now For Something
Completely Different
9
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
January 24, 2006
>>> x = 1 + 1
>>> x
2
>>> x = 1 + 1.0
>>> x
2.0
>>>
>>> y
Traceback (most recent call last):
File "<pyshell#20>", line 1, in -toplevely
NameError: name 'y' is not defined
>>> y = None
>>> y
>>> y == None
True
>>> del y
>>> y
Traceback (most recent call last):
File "<pyshell#25>", line 1, in -toplevely
NameError: name 'y' is not defined
>>>
And Now For Something
Completely Different
10
Lists
• Python’s array like
object is a list
– Uses [ ]
– Subscripted like arrays
in C (zero based)
– Mutable
>>>
>>>
5
>>>
>>>
[4,
>>>
3
>>>
z = [4, 5, 6]
z[1]
z[1] = 7
z
7, 6]
len( z )
– Use len(L) to get the
length of the list
January 24, 2006
And Now For Something
Completely Different
11
Lists
• Indexing
– Uses bracket notation
– Indexes start at 0…can have a negative index
name = [“Cleese”, “John”]
print name[1], name[0]
name[0] = “Smith”
x=[[1,2,3],[y,z],[[[]]]]
0
“A”
-5
January 24, 2006
1
“B”
-4
# example of strings in a list
# prints “John Cleese”
# example of lists in a list
2
“C”
-3
3
“D”
-2
4
“E”
-1
And Now For Something
Completely Different
12
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"]
0
1
“A”
-5
January 24, 2006
-4
2
“B”
3
“C”
-3
-2
5
4
“D”
“E”
-1
And Now For Something
Completely Different
13
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
14
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
January 24, 2006
>>>
>>>
'a'
>>>
3
>>>
x = "abc"
x[0]
len(x)
x[0] = 'd'
Traceback (most recent
call last):
File "<pyshell#34>",
line 1, in -toplevelx[0] = 'd'
TypeError: object doesn't
support item assignment
>>>
And Now For Something
Completely Different
15
Converting Values
• String values can be
converted to integers
using the int() function
• Example
• String values can be
converted to floating
points using the float()
function
x = int( “10” )
y = float( “10”)
yy = float (10)
Z = str(3.14159)
• Ints and floats can be
converted to string values
str() function
January 24, 2006
And Now For Something
Completely Different
16
String Methods
upper()
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
17
Tuples
• Tuples are like lists
– Immutable
– Use ( ) notation instead of [ ]’s
for creation
– Uses [ ] notation for indexing
and slicing
January 24, 2006
>>> 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 toplevelx[1] = 'Michael'
TypeError: object doesn't support
item assignment
>>>
And Now For Something
Completely Different
18
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
19
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
20
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
21
Other Assignment Operators
• Augmented assignment operators
– A combination of assignment and a mathematical
operation
•
•
•
•
•
*=
/=
%=
+=
-=
January 24, 2006
x *= 5
x /= 5
x %=5
x += 5
x -= 5
And Now For Something
Completely Different
x=x*5
x=x/5
x=x%5
x=x+5
x=x-5
22
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 shortcircuited
•
•
•
•
•
•
•
•
•
•
1 < 2
1 > 2
[1,2] < [3,4]
[1,2] == [1,2]
“ab” == “a” + “b”
(1,2) == [1,2]
not []
not [1,2,3]
not ‘’
not ‘ab’
# False
#
#
#
#
#
#
#
#
#
True
False
True
True
True
False
True
False
True
– Can do lexicographic
comparison of sequences
(lists, strings, tuples)
January 24, 2006
And Now For Something
Completely Different
23
Statements and Control
Structures
January 24, 2006
And Now For Something
Completely Different
24
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
25
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
26
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
27
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
28
For Loops
• More examples of for loops
# print values in a list
for value in [1, 2, 3, 4, 5, 4, 3, 2, 1]:
print value
# print 10 thru 19
for value in range(10,20):
print value
# print 10 12 14 16 18
for value in range(10, 20, 2):
print value
January 24, 2006
And Now For Something
Completely Different
29
Input, Output, and File Access
January 24, 2006
And Now For Something
Completely Different
30
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
31
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
32
File Input / Output
• Example
filespec = open( “somefile”, “r” )
s = filespec.readline()
s = filespec.readlines()
# read one line
# read all lines
filespec.close()
January 24, 2006
And Now For Something
Completely Different
33
File Input / Output
• Example
filespec = open( “somefile”, “w” )
filespec.writeline(s)
filespec.writelines(l)
# write one string
# write string list
filespec.close()
January 24, 2006
And Now For Something
Completely Different
34
Functions
January 24, 2006
And Now For Something
Completely Different
35
Functions
• Use the keyword def
–
–
–
–
Passing parameters
Named arguments
Default values
Variable scoping
def square(x):
return x*x
print square(2)
January 24, 2006
# prints out 4
And Now For Something
Completely Different
36
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
37
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
38
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
39
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
40
Classes and Objects
January 24, 2006
And Now For Something
Completely Different
41
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
42
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
43
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
44
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
45
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
46
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)
>>>
January 24, 2006
And Now For Something
Completely Different
47