950 likes | 1.26k Views
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
E N D
Object-Oriented Programming in PythonGoldwasser and LetscherChapter 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
The Python Prompt >>> • This lets us know that the interpreter awaits our next command Object-Oriented Programming in Python
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
Instantiation >>> groceries = list() >>> list Constructs a new instance from the list class (notice the parentheses in the syntax) Object-Oriented Programming in Python
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
Calling a Method >>> groceries = list() >>> groceries.append('bread') >>> groceries list 'bread' Object-Oriented Programming in Python
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
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 Method Calling Syntax groceries.append('bread') Object-Oriented Programming in Python
Common Errors >>> groceries.append() What's the mistake? Traceback (most recent call last): File "<stdin>", line 1, in -toplevel- TypeError: append() takes exactly one argument (0 given) >>> Traceback (most recent call last): File "<stdin>", line 1, in -toplevel- NameError: name 'bread' is not defined groceries.append(bread) What's the mistake? Object-Oriented Programming in Python
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
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', 'Donald', 'Eric', 'Nell'] waitlist.insert(1, 'Donald') >>> >>> waitlist ['Kim', 'Eric', 'Nell'] >>> Object-Oriented Programming in Python
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
The remove Method What if Eric gets tired of waiting? >>> waitlist ['Kim', 'Donald', 'Eric', 'Nell'] >>> waitlist ['Kim', 'Donald', 'Nell'] >>> waitlist.remove('Eric') >>> Object-Oriented Programming in Python
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
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
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
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
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
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
Negative Indices >>> waitlist ['Kim', 'Donald', 'Eric', 'Nell'] >>> waitlist[-1] 'Nell' >>> waitlist[-3] 'Donald' >>> waitlist[-4] 'Kim' >>> Object-Oriented Programming in Python
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
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
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
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
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
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
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
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
Common behaviors greeting = 'How do you do?' • len(greeting) returns 14 • 'yo' in greeting returns True • greeting.count('do')returns2 • greeting.index('do')returns4 • greeting[2] returns'w' Object-Oriented Programming in Python
alphabet[9:20:3] returns'jmps' Slicing Slicing is a generalization of indexing that is supported by strings (and lists too). 1111111111222222 01234567890123456789012345 alphabet = 'abcdefghijklmnopqrstuvwxyz' Object-Oriented Programming in Python
alphabet[9:20:3] returns'jmps' 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
alphabet[9:20:3] returns'jmps' 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
alphabet[9:20:3] returns'jmps' 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
alphabet[9:20:3] returns'jmps' 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
alphabet[9:20:3] returns'jmps' 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
alphabet[9:20:3] returns'jmps' 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
alphabet[9:20:3] returns'jmps' 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
alphabet[9:20:3] returns'jmps' 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
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
Example: lower( ) >>> formal = 'Hello' >>> formal str 'Hello' Object-Oriented Programming in Python
Example: lower( ) >>> formal = 'Hello' >>> informal = formal.lower() >>> formal informal str str 'Hello' 'hello' Note that formal is unchanged Object-Oriented Programming in Python
Reassigning an Identifier >>> person = 'Alice' >>> person str 'Alice' Object-Oriented Programming in Python
Reassigning an Identifier >>> person = 'Alice' >>> person = person.lower() >>> person str str 'Alice' 'alice' Object-Oriented Programming in Python
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
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
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
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
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
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