Upload
baina
View
100
Download
0
Tags:
Embed Size (px)
DESCRIPTION
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 - PowerPoint PPT Presentation
Citation preview
Getting Started with Python
Object-Oriented Programming in PythonGoldwasser and Letscher
Chapter 2
Object-Oriented Programming in Python 2-2
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-3
The Python Prompt
>>>
• This lets us know that the interpreter awaits our next command
Object-Oriented Programming in Python 2-4
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-5
Instantiation
>>> groceries = list()>>>
Constructs a new instance from the list class(notice the parentheses in the syntax)
list
Object-Oriented Programming in Python 2-6
Assignment Statement
>>> groceries = list()>>>
groceries serves as an identifier for the newly constructed object (like a “sticky label”)
listgroceries
Object-Oriented Programming in Python 2-7
Calling a Method
>>> groceries = list()>>> groceries.append('bread')>>>
list
'bread'
groceries
Object-Oriented Programming in Python 2-8
Displaying Internals
>>> groceries = list()>>> groceries.append('bread')>>>
When working in the interpreter, we do not directly "see" the internal picture. But we can request a textual representation.
groceries ['bread'] interpreter's response>>>
Object-Oriented Programming in Python 2-9
Method Calling Syntax
groceries.append('bread')
object
• There may be many objects to choose from
method
• The given object may support many methods
parameters
• Use of parameters depends upon the method
Object-Oriented Programming in Python 2-10
Traceback (most recent call last): File "<stdin>", line 1, in -toplevel-NameError: name 'bread' is not defined
Common Errors
Traceback (most recent call last): File "<stdin>", line 1, in -toplevel-TypeError: append() takes exactly one argument (0 given)
>>> groceries.append(bread) What's the mistake?
>>> groceries.append() What's the mistake?
Object-Oriented Programming in Python 2-11
The append Method
>>> waitlist = list()>>> waitlist.append('Kim')>>> waitlist.append('Eric')>>> waitlist.append('Nell')
New item added to the end of the list(much like a restaurant's waitlist)
>>> waitlist['Kim', 'Eric', 'Nell']
Object-Oriented Programming in Python 2-12
waitlist['Kim', 'Donald', 'Eric', 'Nell']
The insert Method
waitlist.insert(1, 'Donald')>>>
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']>>>
Object-Oriented Programming in Python 2-13
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-14
waitlist['Kim', 'Donald', 'Nell']>>>
>>> waitlist['Kim', 'Donald', 'Eric', 'Nell']>>>
The remove Method
What if Eric gets tired of waiting?
waitlist.remove('Eric')>>>
Object-Oriented Programming in Python 2-15
• 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']
The remove Method
Object-Oriented Programming in Python 2-16
• 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
Return values
Object-Oriented Programming in Python 2-17
>>> groceries['milk', 'bread', 'cheese', 'bread']>>>
The count method
2 response from the interpreter>>>
groceries.count('bread')
groceries.count('milk')1>>> groceries.count('apple')0>>>
Object-Oriented Programming in Python 2-18
>>> groceries['milk', 'bread', 'cheese', 'bread']>>>
Saving a Return Value
• We can assign an identifier to the returned object
numLoaves = groceries.count('bread')>>>
• Notice that it is no longer displayed by interpreter
numLoaves>>> 2
• Yet we can use it in subsequent commands
Object-Oriented Programming in Python 2-19
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-20
>>> waitlist['Kim', 'Donald', 'Eric', 'Nell']>>>
Accessing a list element
'Donald'>>>
waitlist[1]
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-21
>>> waitlist['Kim', 'Donald', 'Eric', 'Nell']>>>
Negative Indices
'Nell'>>>
waitlist[-1]
waitlist[-3]'Donald'>>> waitlist[-4]'Kim'>>>
Object-Oriented Programming in Python 2-22
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-23
favoriteColors
['red', 'green', 'purple', 'blue']
>>>
Copying Lists
• The list( ) constructor is useful for making a new list modeled upon an existing sequence
>>> favoriteColors = ['red', 'green', 'purple', 'blue']
>>>
primaryColors
['red', 'green', 'blue']
>>>
primaryColors.remove('purple')
>>>
primaryColors = list(favoriteColors) a copy
>>>
Object-Oriented Programming in Python 2-24
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-25
The range functionrange(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-26
Many useful behaviors
These will become familiar with more practice.
• 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
Object-Oriented Programming in Python 2-27
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-28
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-29
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-30
Common behaviors
greeting = 'How do you do?'
• len(greeting) returns 14• 'yo' in greeting returns
True
• greeting.count('do') returns 2
• greeting.index('do') returns 4
• greeting[2] returns 'w'
Object-Oriented Programming in Python 2-31
Slicing is a generalization of indexing that is supported by strings (and lists too).
Slicing
1111111111222222 01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
Object-Oriented Programming in Python 2-32
Slicing
1111111111222222 01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
Slicing is a generalization of indexing that is supported by strings (and lists too).
alphabet[4] returns 'e'
Object-Oriented Programming in Python 2-33
Slicing
1111111111222222 01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
Slicing is a generalization of indexing that is supported by strings (and lists too).
alphabet[4:13] returns 'efghijklm'(starting at 4, going up to but not including 13)
Object-Oriented Programming in Python 2-34
Slicing
1111111111222222 01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
Slicing is a generalization of indexing that is supported by strings (and lists too).
alphabet[ :6] returns 'abcdef'(starting at beginning going up to but not including 6)
Object-Oriented Programming in Python 2-35
Slicing
1111111111222222 01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
Slicing is a generalization of indexing that is supported by strings (and lists too).
alphabet[23:] returns 'xyz'(starting at 23 going all the way to the end)
Object-Oriented Programming in Python 2-36
Slicing
1111111111222222 01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
Slicing is a generalization of indexing that is supported by strings (and lists too).
alphabet[9:20:3] returns 'jmps'(starting at 9, stopping before 20, stepping by 3)
Object-Oriented Programming in Python 2-37
Slicing
1111111111222222 01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
Slicing is a generalization of indexing that is supported by strings (and lists too).
alphabet[17:5:-3] returns 'roli'(starting at 17, toward but not with 5, stepping by -3)
Object-Oriented Programming in Python 2-38
Slicing
1111111111222222 01234567890123456789012345
alphabet = 'abcdefghijklmnopqrstuvwxyz'
Slicing is a generalization of indexing that is supported by strings (and lists too).
alphabet[ : :-1] 'zyxwvutsrqponmlkjihgfedcba'(everything, but in reverse order)
Object-Oriented Programming in Python 2-39
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-40
Differences: list and str
• We cannot change an existing string.
• However, we can create new strings based upon existing ones.
• List are mutable; strings are immutable
(allows Python to optimize the internals)
Object-Oriented Programming in Python 2-41
Example: lower( )
>>> formal = 'Hello'>>>
str
'Hello'
formal
Object-Oriented Programming in Python 2-42
Example: lower( )
>>> formal = 'Hello'>>> informal = formal.lower()>>>
str
'hello'
informalstr
'Hello'
formal
Note that formal is unchanged
Object-Oriented Programming in Python 2-43
Reassigning an Identifier
>>> person = 'Alice'>>>
str
'Alice'
person
Object-Oriented Programming in Python 2-44
Reassigning an Identifier
>>> person = 'Alice'>>> person = person.lower()>>>
str
'alice'
personstr
'Alice'
Object-Oriented Programming in Python 2-45
Creating New Strings
• greeting.lower( ) • greeting.upper( ) • greeting.capitalize( )• greeting.strip( )• greeting.center(30) • greeting.replace('hi','hello')
Each of the following leaves the original string unchanged, returning a new string as a result.
Object-Oriented Programming in Python 2-46
Additional string methods
• greeting.islower( ) not to be confused with lower( ) • greeting.isupper( ) • greeting.isalpha( )• greeting.isdigit( )• greeting.startswith(pattern) • greeting.endswith(pattern)
Strings support other methods that are specific to the context of textual information
Object-Oriented Programming in Python 2-47
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-48
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-49
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-50
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-51
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-52
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-53
The tuple ClassYet 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-54
The tuple ClassLiteral 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-55
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-56
Arithmetic Operators
• x + y addition• x - y subtraction• x * y multiplication• x / y "true" division• x // y "integer" division• x % y modulo operator ("remainder")• x ** y x raised to the power y• abs(x) absolute value of x
Object-Oriented Programming in Python 2-57
Comparison Operators
• x == y True if x equals y• x != y True if x does not equal y• x < y True if x strictly less than y• x <= y True if x less than or equal to y• x > y True if x strictly greather than y• x >= y True if x greater than or equal to y• cmp(x,y) Returns-1 if x < y
0 if x == y +1 if x > y
Object-Oriented Programming in Python 2-58
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-59
Immutable Objects
>>> x = 5>>>
int
5
x
Object-Oriented Programming in Python 2-60
Immutable Objects
>>> x = 5>>> x = x + 1>>>
int
6
xint
5
Object-Oriented Programming in Python 2-61
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 floating-point value 35.0, nor the string '35'.
Object-Oriented Programming in Python 2-62
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-63
Type Conversions
• float(35) results in 35.0• str(35) results in '35'• int('35') results in 35• int('ten') results in an error• list('ten') results in ['t', 'e', 'n']• int(35.3) results in 35• int(35.9) results in 35• int(-35.9) results in -35
Object-Oriented Programming in Python 2-64
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-65
Pure Functions
• Although we highlighted the traditional object-oriented 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-66
Pure Functions• pow(x, y) same as x**y• abs(value) absoulte value• max(a, b, c, d) maximum of parameters• max(sequence) maximum within a sequence• min(a, b, c, d) minimum of parameters• min(sequence) minimum within a sequence• sum(sequence) sum of numeric sequence• len(sequence) length of a sequence• sorted(sequence) sorted copy of a sequence• ord(char) alphabet code for given char• chr(code) character for given alphabet code
Object-Oriented Programming in Python 2-67
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-68
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 we use a qualified name
3.141592635897931
>>> math.sqrt(2) we use a qualified name
1.41421356237
Object-Oriented Programming in Python 2-69
Importing a 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 *
Style #2: import pieces from the module
Object-Oriented Programming in Python 2-70
Expressions
18 + 5 + 2
Multiple operations can be expressed at once
+
518
( )
23
Object-Oriented Programming in Python 2-71
Expressions
23
+
518
23
25
Multiple operations can be expressed at once
2
+( )+ 2
Object-Oriented Programming in Python 2-72
Expressions
25
+
518
23
25
Multiple operations can be expressed at once
2
+
((18 + 5) + 2)
addition is left-associative
Object-Oriented Programming in Python 2-73
Precedence
1 + 2 * 3
Some operators are given precedence over others
*
32
( ) +
1
( )
Object-Oriented Programming in Python 2-74
Using Parentheses
(1 + 2) * 3
You can control the evaluation by giving explicit parentheses in your expressions.
+
21
*
3
Object-Oriented Programming in Python 2-75
Assignment Operator
score = (1 + 2) * 3
The assignment operator = is simply an operator with very low precedence. Everything on the righthand side is evaluated before the assignment is performed.
+
2
score *
3
=
1
Object-Oriented Programming in Python 2-76
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-77
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 False True True True False
Object-Oriented Programming in Python 2-78
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-79
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-80
Source Code
>>> groceries = list( )
>>> groceries.append('bread')
>>> groceries.append('milk')
>>> groceries.append('cheese')
InterpreterSession
groceries = list( )
groceries.append('bread')
groceries.append('milk')
groceries.append('cheese')
Source Codedemo.py
Object-Oriented Programming in Python 2-81
Executing Source Code
• Once we have saved our commands in a file perhaps named demo.py, we execute it by– At operating system command promptpython 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-82
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-83
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-84
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 (notice no quotation marks)
Object-Oriented Programming in Python 2-85
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-86
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-87
Receiving Input
As a programmer working in the interpreter, we can set variables as we wish.>>> fruit = 'apple'
fruit = raw_input('Pick a fruit: ')
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
Object-Oriented Programming in Python 2-88
Receiving Input
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).
fruit = raw_input('Pick a fruit: ')print 'You picked', fruit
Pick a fruit: appleYou picked apple
Object-Oriented Programming in Python 2-89
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-90
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 listgroceries = list( ) # it is initially empty
Object-Oriented Programming in Python 2-91
Case Study: Date Format
monthNames = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
# get input from useroriginal = 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 + ', ' + yearprint alternate