Download Getting Started with Python

Document related concepts
no text concepts found
Transcript
Object-Oriented Programming in Python
Goldwasser and Letscher
Chapter 2
Getting Started with Python
The Python Interpreter
• A piece of software that executes
commands for the Python language
• Start the interpreter by typing python at a
command prompt
• Many developers use an Integrated
Development Environment for Python
known as IDLE
Object-Oriented Programming in Python
2-2
The Python Prompt
>>>
• This lets us know that the interpreter awaits
our next command
Object-Oriented Programming in Python
2-3
Our First Example
>>> groceries = list()
>>>
• We see a new Python prompt, so the
command has completed.
• But what did it do?
Object-Oriented Programming in Python
2-4
Instantiation
>>> groceries = list()
>>>
list
Constructs a new instance from the list class
(notice the parentheses in the syntax)
Object-Oriented Programming in Python
2-5
Assignment Statement
>>> groceries = list()
>>>
groceries
list
groceries serves as an identifier for the newly
constructed object (like a “sticky label”)
Object-Oriented Programming in Python
2-6
Calling a Method
>>> groceries = list()
>>> groceries.append('bread')
>>>
groceries
list
'bread'
Object-Oriented Programming in Python
2-7
Displaying Internals
When working in the interpreter, we do not
directly "see" the internal picture. But we
can request a textual representation.
>>> groceries = list()
>>> groceries.append('bread')
>>> groceries
['bread']
 interpreter's response
>>>
Object-Oriented Programming in Python
2-8
Method Calling Syntax
groceries.append('bread')
object
method
parameters
• There may be many objects to choose from
• The given object may support many methods
• Use of parameters depends upon the method
Object-Oriented Programming in Python
2-9
Common Errors
>>> groceries.append()
What's the mistake?
Traceback (most recent call last):
File "<stdin>", line 1, in -toplevelTypeError: append() takes exactly one argument (0 given)
>>> groceries.append(bread)
What's the mistake?
Traceback (most recent call last):
File "<stdin>", line 1, in -toplevelNameError: name 'bread' is not defined
Object-Oriented Programming in Python
2-10
The append Method
New item added to the end of the list
(much like a restaurant's waitlist)
>>> waitlist = list()
>>> waitlist.append('Kim')
>>> waitlist.append('Eric')
>>> waitlist.append('Nell')
>>> waitlist
['Kim', 'Eric', 'Nell']
Object-Oriented Programming in Python
2-11
The insert Method
Can insert an item in an arbitrary place using a
numeric index to describe the position. An
element's index is the number of items before it.
>>> waitlist
['Kim', 'Eric', 'Nell']
>>> waitlist.insert(1, 'Donald')
>>> waitlist
['Kim', 'Donald', 'Eric', 'Nell']
Object-Oriented Programming in Python
2-12
Zero-Indexing
By this definition,
• the first element of the list has index 0
• the second element has index 1
• the last element has index (length - 1)
We call this convention zero-indexing.
(this is a common point of confusion)
Object-Oriented Programming in Python
2-13
The remove Method
What if Eric gets tired of waiting?
>>> waitlist
['Kim', 'Donald', 'Eric', 'Nell']
>>> waitlist.remove('Eric')
>>> waitlist
['Kim', 'Donald', 'Nell']
>>>
Object-Oriented Programming in Python
2-14
The remove Method
• Notice that we didn't have to identify where
the item is; the list will find it.
• If it doesn't exist, a ValueError occurs
• With duplicates, the earliest is removed
>>> groceries
['milk', 'bread', 'cheese', 'bread']
>>> groceries.remove('bread')
>>> groceries
['milk', 'cheese', 'bread']
Object-Oriented Programming in Python
2-15
Return values
• Thus far, all of the methods we have seen
have an effect on the list, but none return
any direct information to us.
• Many other methods provide an explicit
return value.
• As our first example: the count method
Object-Oriented Programming in Python
2-16
The count method
>>> groceries
['milk', 'bread', 'cheese', 'bread']
>>> groceries.count('bread')
2
 response from the interpreter
>>> groceries.count('milk')
1
>>> groceries.count('apple')
0
>>>
Object-Oriented Programming in Python
2-17
Saving a Return Value
• We can assign an identifier to the returned object
>>> groceries
['milk', 'bread', 'cheese', 'bread']
>>> numLoaves = groceries.count('bread')
>>> numLoaves
>>> 2
• Notice that it is no longer displayed by interpreter
• Yet we can use it in subsequent commands
Object-Oriented Programming in Python
2-18
Operators
• Most behaviors are invoked with the typical
"method calling" syntax of object.method( )
• But Python uses shorthand syntax for many of the
most common behaviors (programmers don't like
extra typing)
• For example, the length of a list can be queried as
len(groceries) although this is really shorthand
for a call groceries.__len__( )
Object-Oriented Programming in Python
2-19
Accessing a list element
>>> waitlist
['Kim', 'Donald', 'Eric', 'Nell']
>>> waitlist[1]
'Donald'
>>> waitlist[3]
'Nell'
>>> waitlist[4]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
Object-Oriented Programming in Python
2-20
Negative Indices
>>> waitlist
['Kim', 'Donald', 'Eric', 'Nell']
>>> waitlist[-1]
'Nell'
>>> waitlist[-3]
'Donald'
>>> waitlist[-4]
'Kim'
>>>
Object-Oriented Programming in Python
2-21
List Literals
• We originally used the syntax list( ) to create a
new empty list. For convenience, there is a
shorthand syntax known as a list literal.
groceries = [ ]
(experienced programmers like to type less!)
• List literals can also be used to create non-empty
lists, using a syntax similar to the one the
interpreter uses when displaying a list.
groceries = ['cheese', 'bread', 'milk']
Object-Oriented Programming in Python
2-22
Copying Lists
• The list( ) constructor is useful for making a
new list modeled upon an existing sequence
>>> favoriteColors = ['red', 'green', 'purple', 'blue']
>>> primaryColors = list(favoriteColors)
 a copy
>>> primaryColors.remove('purple')
>>> primaryColors
['red', 'green', 'blue']
>>> favoriteColors
['red', 'green', 'purple', 'blue']
>>>
Object-Oriented Programming in Python
2-23
The range function
• Lists of integers are commonly needed.
Python supports a built-in function named
range to easily construct such lists.
• There are three basic forms:
range(stop)
goes from zero up to but not including stop
>>> range(5)
[0, 1, 2, 3, 4]
Object-Oriented Programming in Python
2-24
The range function
range(start, stop)
begins with start rather than zero
>>> range(23, 28)
[23, 24, 25, 26, 27]
range(start, stop, step)
uses the given step size
>>> range(23, 35, 4)
[23, 27, 31]
>>> range(8, 3, -1)
[8, 7, 6, 5, 4]
Object-Oriented Programming in Python
2-25
Many useful behaviors
• groceries.pop( )
remove last element
• groceries.pop(i)
remove ith element
• groceries.reverse( )
reverse the list
• groceries.sort( )
sort the list
• 'milk' in groceries
does list contain?
• groceries.index('cereal')
find leftmost match
These will become familiar with more practice.
Object-Oriented Programming in Python
2-26
Documentation
• See Section 2.2.6 of the book for more
details and a table summarizing the most
commonly used list behaviors.
• You may also type help(list) from within
the Python interpreter for documentation, or
for a specific method as help(list.insert)
Object-Oriented Programming in Python
2-27
Python's str class
• A list can represent any sequence of objects
• A very common need in computing is for a
sequence of text characters.
• There is a specialized class, named str,
devoted to manipulating character strings.
Object-Oriented Programming in Python
2-28
String literals
• Can enclose in single quotes: 'bread'
• Can enclose in double quotes: "bread"
• This choice helps when you want to use a
single or double quote as a character within
the string: "Who's there?"
• Can embed a newline character using an
escape character \n as in:
"Knock Knock\nWho's there?"
Object-Oriented Programming in Python
2-29
Common behaviors
greeting = 'How do you do?'
• len(greeting)
• 'yo' in greeting
• greeting.count('do')
• greeting.index('do')
• greeting[2]
Object-Oriented Programming in Python
returns 14
returns True
returns 2
returns 4
returns 'w'
2-30
Slicing
Slicing is a generalization of indexing that is
supported by strings (and lists too).
1111111111222222
01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
Object-Oriented Programming in Python
2-31
Slicing
Slicing is a generalization of indexing that is
supported by strings (and lists too).
1111111111222222
01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet[4] returns 'e'
Object-Oriented Programming in Python
2-32
Slicing
Slicing is a generalization of indexing that is
supported by strings (and lists too).
1111111111222222
01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet[4:13] returns 'efghijklm'
(starting at 4, going up to but not including 13)
Object-Oriented Programming in Python
2-33
Slicing
Slicing is a generalization of indexing that is
supported by strings (and lists too).
1111111111222222
01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet[ :6] returns 'abcdef'
(starting at beginning going up to but not including 6)
Object-Oriented Programming in Python
2-34
Slicing
Slicing is a generalization of indexing that is
supported by strings (and lists too).
1111111111222222
01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet[23:] returns 'xyz'
(starting at 23 going all the way to the end)
Object-Oriented Programming in Python
2-35
Slicing
Slicing is a generalization of indexing that is
supported by strings (and lists too).
1111111111222222
01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet[9:20:3] returns 'jmps'
(starting at 9, stopping before 20, stepping by 3)
Object-Oriented Programming in Python
2-36
Slicing
Slicing is a generalization of indexing that is
supported by strings (and lists too).
1111111111222222
01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet[17:5:-3] returns 'roli'
(starting at 17, toward but not with 5, stepping by -3)
Object-Oriented Programming in Python
2-37
Slicing
Slicing is a generalization of indexing that is
supported by strings (and lists too).
1111111111222222
01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphabet[ : :-1] 'zyxwvutsrqponmlkjihgfedcba'
(everything, but in reverse order)
Object-Oriented Programming in Python
2-38
Summary of Slicing
Notice that convention for slicing
alphabet[start:stop:step]
uses indices akin to that of
range(start, stop, step)
Object-Oriented Programming in Python
2-39
Differences: list and str
• List are mutable; strings are immutable
(allows Python to optimize the internals)
• We cannot change an existing string.
• However, we can create new strings based
upon existing ones.
Object-Oriented Programming in Python
2-40
Example: lower( )
>>> formal = 'Hello'
>>>
formal
str
'Hello'
Object-Oriented Programming in Python
2-41
Example: lower( )
>>> formal = 'Hello'
>>> informal = formal.lower()
>>>
formal
str
'Hello'
informal
str
'hello'
Note that formal is unchanged
Object-Oriented Programming in Python
2-42
Reassigning an Identifier
>>> person = 'Alice'
>>>
person
str
'Alice'
Object-Oriented Programming in Python
2-43
Reassigning an Identifier
>>> person = 'Alice'
>>> person = person.lower()
>>>
str
'Alice'
Object-Oriented Programming in Python
person
str
'alice'
2-44
Creating New Strings
Each of the following leaves the original string
unchanged, returning a new string as a result.
•
•
•
•
•
•
greeting.lower( )
greeting.upper( )
greeting.capitalize( )
greeting.strip( )
greeting.center(30)
greeting.replace('hi','hello')
Object-Oriented Programming in Python
2-45
Additional string methods
Strings support other methods that are specific to
the context of textual information
•
•
•
•
•
•
greeting.islower( )
not to be confused with lower( )
greeting.isupper( )
greeting.isalpha( )
greeting.isdigit( )
greeting.startswith(pattern)
greeting.endswith(pattern)
Object-Oriented Programming in Python
2-46
Converting between
strings and lists
• To support text processing, the str class has
methods to split and rejoin strings.
• split is used to divide a string into a list of
pieces based upon a given separator.
• join is used to assemble a list of strings and
a separator into a composite string.
Object-Oriented Programming in Python
2-47
The split method
By default, the pieces are based on dividing
the original around any form of whitespace
(e.g., spaces, tabs, newlines)
>>> request = 'eggs and milk and apples'
>>> request.split( )
['eggs', 'and', 'milk', 'and', 'apples']
Object-Oriented Programming in Python
2-48
The split method
Some other separator can be specified as an
optional parameter to split. That string will be
used verbatim.
>>> request = 'eggs and milk and apples'
>>> request.split('and')
['eggs ', ' milk ', ' apples']
^
^
^
^
(note well the spaces that remain)
Object-Oriented Programming in Python
2-49
The split method
Here is the same example, but with spaces
embedded within the separator string.
>>> request = 'eggs and milk and apples'
>>> request.split(' and ')
['eggs', 'milk', 'apples']
Object-Oriented Programming in Python
2-50
The join method
The join method takes a sequence of strings
and combines them using a given string
separator between each pair. Formally, this
method is invoked upon the separator.
>>> guests = ['John', 'Mary', 'Amy']
>>> conjunction = ' and '
>>> conjunction.join(guests)
'John and Mary and Amy'
Object-Oriented Programming in Python
2-51
The join method
The separator is often expressed as a literal.
>>> guests = ['John', 'Mary', 'Amy']
>>> ' and '.join(guests)
'John and Mary and Amy'
The sequence could be a string of characters.
>>> '-'.join('respect')
'r-e-s-p-e-c-t'
Object-Oriented Programming in Python
2-52
The tuple Class
Yet another built-in sequence class.
A tuple is an immutable version of a list.
The benefit is that Python can optimize the internal
mechanisms, knowing that the contents of the
sequence remain fixed.
Object-Oriented Programming in Python
2-53
The tuple Class
Literal form uses parentheses:
>>> skyBlue = (136, 207, 236)
Supported behaviors are a subset of those supported
by lists, most prominently indexing, slicing, and
length.
Object-Oriented Programming in Python
2-54
Numeric Types
• int
integers (fixed precision)
5, -2273, 299792458
• long
integers (arbitrary magnitudes)
• float
floating-point representation
3.14159, 0.125, -0.618, 3.0
• All of these are immutable and among the
most primitives of Python's classes
Object-Oriented Programming in Python
2-55
Arithmetic Operators
•
•
•
•
•
•
•
•
x+y
x-y
x*y
x/y
x // y
x%y
x ** y
abs(x)
addition
subtraction
multiplication
"true" division
"integer" division
modulo operator ("remainder")
x raised to the power y
absolute value of x
Object-Oriented Programming in Python
2-56
Comparison Operators
•
•
•
•
•
•
•
x == y
x != y
x<y
x <= y
x>y
x >= y
cmp(x,y)
True if x equals y
True if x does not equal y
True if x strictly less than y
True if x less than or equal to y
True if x strictly greather than y
True if x greater than or equal to y
Returns
-1 if x < y
0 if x == y
+1 if x > y
Object-Oriented Programming in Python
2-57
Operators for str and list
Strings and lists support some operators
'over' + 'load'
results in 'overload'
'HO' * 3
results in 'HOHOHO'
[0]*4
results in [0, 0, 0, 0]
'hello' == 'Hello'
results in False
'hello' > 'goodbye' results in True
'good' < 'goodbye' results in True
Object-Oriented Programming in Python
2-58
Immutable Objects
>>> x = 5
>>>
x
int
5
Object-Oriented Programming in Python
2-59
Immutable Objects
>>> x = 5
>>> x = x + 1
>>>
int
5
Object-Oriented Programming in Python
x
int
6
2-60
Type Conversions
• The internal encoding of an object depends
upon its type.
• So the bits representing the integer 35 are
not the same as those representing floatingpoint value 35.0, nor the string '35'.
Object-Oriented Programming in Python
2-61
Type Conversions
• Often we want to "convert" a piece of data to
another type. We do not technically change the
original data, rather we construct an instance of
the new type with an appropriate value.
• For example, the expression float(35)
results in the floating-point value 35.0
Object-Oriented Programming in Python
2-62
Type Conversions
•
•
•
•
•
•
•
•
float(35)
str(35)
int('35')
int('ten')
list('ten')
int(35.3)
int(35.9)
int(-35.9)
results in
results in
results in
results in
results in
results in
results in
results in
Object-Oriented Programming in Python
35.0
'35'
35
an error
['t', 'e', 'n']
35
35
-35
2-63
The round function
• int(x) truncates any fractional part. If we prefer,
we can first use the round function.
• round(3.8) results in 4.0
• Notice that the result is technically a float.
• int(round(3.8)) results in 4
• With optional parameter, can round to some other
number of digits.
• round(3.14159, 3) results in 3.142
Object-Oriented Programming in Python
2-64
Pure Functions
• Although we highlighted the traditional objectoriented syntax object.method(param), notice
that we have used a different syntax for some
functions.
• We write round(val) rather than val.round( )
• These functions are not methods of a class. We
refer to them as pure functions.
Object-Oriented Programming in Python
2-65
Pure Functions
•
•
•
•
•
•
•
•
•
•
•
pow(x, y)
abs(value)
max(a, b, c, d)
max(sequence)
min(a, b, c, d)
min(sequence)
sum(sequence)
len(sequence)
sorted(sequence)
ord(char)
chr(code)
Object-Oriented Programming in Python
same as x**y
absoulte value
maximum of parameters
maximum within a sequence
minimum of parameters
minimum within a sequence
sum of numeric sequence
length of a sequence
sorted copy of a sequence
alphabet code for given char
character for given alphabet code
2-66
Modules
• In addition to the built-in classes and
functions, Python supports many additional
tools in libraries known as modules.
• To use these tools, they must first be
formally imported.
• Commonly used modules:
math, random, time, datetime, re, os, sys
Object-Oriented Programming in Python
2-67
Importing a Module
• As an example, we consider the math
module, which includes constants such as pi
as well as additional functions such as sqrt.
• Style #1: import the module as a whole
>>> import math
>>> math.pi
3.141592635897931
>>> math.sqrt(2)
1.41421356237
Object-Oriented Programming in Python

we use a qualified name

we use a qualified name
2-68
Importing a Module
Style #2: import pieces from the module
>>> from math import sqrt, pi
>>> pi
 we use an unqualified name
3.141592635897931
>>> sqrt(2)
 we use an unqualified name
1.41421356237
It is also possible to import all pieces using a wildcard.
>>> from math import *
Object-Oriented Programming in Python
2-69
Expressions
Multiple operations can be expressed at once
(18 + 5)+ 2
23
+
18
Object-Oriented Programming in Python
5
2-70
Expressions
Multiple operations can be expressed at once
25
+
( 23 + 2 )
2
23
+
18
Object-Oriented Programming in Python
5
2-71
Expressions
Multiple operations can be expressed at once
25
+
25
((18 + 5) + 2)
addition is left-associative
18
Object-Oriented Programming in Python
2
23
+
5
2-72
Precedence
Some operators are given precedence over others
+
(1 +( 2 * 3) )
*
1
2
Object-Oriented Programming in Python
3
2-73
Using Parentheses
You can control the evaluation by giving explicit
parentheses in your expressions.
(1 + 2) * 3
*
+
1
Object-Oriented Programming in Python
3
2
2-74
Assignment Operator
The assignment operator = is simply an operator with
very low precedence. Everything on the righthand
side is evaluated before the assignment is performed.
=
score = (1 + 2) * 3
score
*
+
Object-Oriented Programming in Python
1
3
2
2-75
Boolean Expressions
• We have seen many expressions thus far
that return either True or False.
• Formally, True and False are instances of
the simplest of all Python classes, bool
• Informally, these are called Boolean values,
named after mathematician George Boole.
Object-Oriented Programming in Python
2-76
Logical Operators
x
y
not x x and y x or y x == y x != y
False False True
False False True False
False True
True
False
True False True
True False False
False
True False True
True
True
True
True False
Object-Oriented Programming in Python
True False
2-77
The Python Interpreter
• When learning, we recommend interacting
directly with Python's interpreter.
(experienced programmers do this as well!)
+ Get immediate feedback
-
Must start over each time we begin
Object-Oriented Programming in Python
2-78
Source Code
• Eventually, we want to save our programs in
files known as source code.
• We generally use the same commands that
we might type into the interpreter but save
them in a separate file to be executed.
• Let's look at an example…
Object-Oriented Programming in Python
2-79
Source Code
Interpreter
Session
Source Code
demo.py
>>>
>>>
>>>
>>>
groceries = list( )
groceries.append('bread')
groceries.append('milk')
groceries.append('cheese')
groceries = list( )
groceries.append('bread')
groceries.append('milk')
groceries.append('cheese')
Object-Oriented Programming in Python
2-80
Executing Source Code
• Once we have saved our commands in a file
perhaps named demo.py, we execute it by
– At operating system command prompt
python demo.py
– Depending on operating system
may be able to double-click directly on file's icon
– From within IDLE
Select 'Run Module' or press the F5 key as a shortcut
Object-Oriented Programming in Python
2-81
Issues for Source Code
•
There are three key issues to consider when
running programs from source code.
1. Results displayed from within the interpreter are not
automatically output to the user.
2. We must have a way to gather input from the user
(since the user cannot simply type into the interpreter)
3. We may wish to leave comments for other
programmers in our source code.
Object-Oriented Programming in Python
2-82
Output
An interactive session is like a conversation
between the interpreter and programmer.
>>> waitlist = ['Kim', 'Eric', 'Nell']
>>> waitlist.pop(0)
'Kim'
>>> waitlist
['Eric', 'Nell']
>>>
Yet the interpreter's responses are not displayed if
these commands are executed from source code.
Object-Oriented Programming in Python
2-83
The print Command
Python supports a print command that
explicitly displays output for the user.
waitlist = ['Kim', 'Eric', 'Nell']
print waitlist.pop(0)
User would see output:
Kim
Object-Oriented Programming in Python
(notice no quotation marks)
2-84
The print Command
Multiple arguments can be given (separated
by commas). Output separated with spaces.
waitlist = ['Kim', 'Eric', 'Nell']
print waitlist.pop(0), 'your table is ready.'
User would see output:
Kim your table is ready.
Object-Oriented Programming in Python
2-85
Printing non-string types
If an argument x to print is not a string, it is
automatically converted to one as str(x).
print 'There are', len(waitlist), 'people.'
User would see output:
There are 3 people.
Object-Oriented Programming in Python
2-86
Receiving Input
As a programmer working in the interpreter, we can
set variables as we wish.
>>> fruit = 'apple'
For a user to interact with a program, we need a way
to get information from the user. This can be done
with Python's raw_input function, as in
fruit = raw_input('Pick a fruit: ')
Object-Oriented Programming in Python
2-87
Receiving Input
fruit = raw_input('Pick a fruit: ')
print 'You picked', fruit
The parameter is a prompt displayed to the user. The
result is a string with all characters typed by the user
(up until newline is entered).
Pick a fruit: apple
You picked apple
Object-Oriented Programming in Python
2-88
Receiving Numeric Input
The result of raw_input is always a string. If you
expect that string to designate an integer, you must
explicitly convert the input as follows.
age = int (raw_input(How old are you? '))
Note: if the user's input cannot be properly
converted, an error occurs interrupting the program
(we'll see how to avoid this some other time).
Object-Oriented Programming in Python
2-89
Comments
It is helpful to leave comments within the
source code file, either as a reminder or as a
note for other programmers.
Python will ignore everything after a #
symbol on a given line.
# we need a grocery list
groceries = list( )
# it is initially empty
Object-Oriented Programming in Python
2-90
Case Study: Date Format
monthNames = ('January', 'February', 'March', 'April',
'May', 'June', 'July', 'August', 'September', 'October',
'November', 'December')
# get input from user
original = raw_input('Please enter a date (MM-DD-YYYY): ')
pieces= original.split('-')
month = pieces[0]
# this is a string of numerals (e.g., '10')
day = pieces[1]
year = pieces[2]
alternate = monthNames[int(month)-1] + ' ' + day + ', ' + year
print alternate
Object-Oriented Programming in Python
2-91