Presentation is loading. Please wait.

Presentation is loading. Please wait.

Getting Started with Python Object-Oriented Programming in Python Goldwasser and Letscher Chapter 2.

Similar presentations


Presentation on theme: "Getting Started with Python Object-Oriented Programming in Python Goldwasser and Letscher Chapter 2."— Presentation transcript:

1

2 Getting Started with Python Object-Oriented Programming in Python Goldwasser and Letscher Chapter 2

3 Object-Oriented Programming in Python2-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

4 Object-Oriented Programming in Python2-3 The Python Prompt >>> This lets us know that the interpreter awaits our next command

5 Object-Oriented Programming in Python2-4 Our First Example >>> groceries = list() We see a new Python prompt, so the command has completed. But what did it do?

6 Object-Oriented Programming in Python2-5 Instantiation >>> groceries = list() >>> Constructs a new instance from the list class (notice the parentheses in the syntax) list

7 Object-Oriented Programming in Python2-6 Assignment Statement >>> groceries = list() >>> groceries serves as an identifier for the newly constructed object (like a “sticky label”) list groceries

8 Object-Oriented Programming in Python2-7 Calling a Method >>> groceries = list() >>> groceries.append('bread') >>> list 'bread' groceries

9 Object-Oriented Programming in Python2-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 >>>

10 Object-Oriented Programming in Python2-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

11 Object-Oriented Programming in Python2-10 Traceback (most recent call last): File " ", line 1, in -toplevel- NameError: name 'bread' is not defined Common Errors Traceback (most recent call last): File " ", 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?

12 Object-Oriented Programming in Python2-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']

13 Object-Oriented Programming in Python2-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'] >>>

14 Object-Oriented Programming in Python2-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)

15 Object-Oriented Programming in Python2-14 waitlist ['Kim', 'Donald', 'Nell'] >>> >>> waitlist ['Kim', 'Donald', 'Eric', 'Nell'] >>> The remove Method What if Eric gets tired of waiting? waitlist.remove('Eric') >>>

16 Object-Oriented Programming in Python2-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

17 Object-Oriented Programming in Python2-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

18 Object-Oriented Programming in Python2-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 >>>

19 Object-Oriented Programming in Python2-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

20 Object-Oriented Programming in Python2-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__( )

21 Object-Oriented Programming in Python2-20 >>> waitlist ['Kim', 'Donald', 'Eric', 'Nell'] >>> Accessing a list element 'Donald' >>> waitlist[1] waitlist[3] 'Nell' >>> waitlist[4] Traceback (most recent call last): File " ", line 1, in ? IndexError: list index out of range

22 Object-Oriented Programming in Python2-21 >>> waitlist ['Kim', 'Donald', 'Eric', 'Nell'] >>> Negative Indices 'Nell' >>> waitlist[-1] waitlist[-3] 'Donald' >>> waitlist[-4] 'Kim' >>>

23 Object-Oriented Programming in Python2-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' ]

24 Object-Oriented Programming in Python2-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 >>>

25 Object-Oriented Programming in Python2-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]

26 Object-Oriented Programming in Python2-25 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]

27 Object-Oriented Programming in Python2-26 Many useful behaviors These will become familiar with more practice. groceries.pop( ) remove last element groceries.pop(i) remove i th element groceries.reverse( ) reverse the list groceries.sort( ) sort the list 'milk' in groceries does list contain? groceries.index('cereal') find leftmost match

28 Object-Oriented Programming in Python2-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)

29 Object-Oriented Programming in Python2-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.

30 Object-Oriented Programming in Python2-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?"

31 Object-Oriented Programming in Python2-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'

32 Object-Oriented Programming in Python2-31 Slicing is a generalization of indexing that is supported by strings (and lists too). Slicing 1111111111222222 01234567890123456789012345 alphabet = 'abcdefghijklmnopqrstuvwxyz' alphabet[9:20:3] returns 'jmps'

33 Object-Oriented Programming in Python2-32 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' alphabet[4] returns 'e'

34 Object-Oriented Programming in Python2-33 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' alphabet[4:13] returns 'efghijklm' (starting at 4, going up to but not including 13)

35 Object-Oriented Programming in Python2-34 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' alphabet[ :6] returns 'abcdef' (starting at beginning going up to but not including 6)

36 Object-Oriented Programming in Python2-35 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' alphabet[23:] returns 'xyz' (starting at 23 going all the way to the end)

37 Object-Oriented Programming in Python2-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)

38 Object-Oriented Programming in Python2-37 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' alphabet[17:5:-3] returns 'roli' (starting at 17, toward but not with 5, stepping by -3)

39 Object-Oriented Programming in Python2-38 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' alphabet[ : :-1] 'zyxwvutsrqponmlkjihgfedcba' (everything, but in reverse order)

40 Object-Oriented Programming in Python2-39 Summary of Slicing Notice that convention for slicing alphabet[start:stop:step] uses indices akin to that of range(start, stop, step) alphabet[9:20:3] returns 'jmps'

41 Object-Oriented Programming in Python2-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)

42 Object-Oriented Programming in Python2-41 Example: lower( ) >>> formal = 'Hello' >>> str 'Hello' formal

43 Object-Oriented Programming in Python2-42 Example: lower( ) >>> formal = 'Hello' >>> informal = formal.lower() >>> str 'hello' informal str 'Hello' formal Note that formal is unchanged

44 Object-Oriented Programming in Python2-43 Reassigning an Identifier >>> person = 'Alice' >>> str 'Alice' person

45 Object-Oriented Programming in Python2-44 Reassigning an Identifier >>> person = 'Alice' >>> person = person.lower() >>> str 'alice' person str 'Alice'

46 Object-Oriented Programming in Python2-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.

47 Object-Oriented Programming in Python2-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

48 Object-Oriented Programming in Python2-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.

49 Object-Oriented Programming in Python2-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']

50 Object-Oriented Programming in Python2-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)

51 Object-Oriented Programming in Python2-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']

52 Object-Oriented Programming in Python2-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'

53 Object-Oriented Programming in Python2-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'

54 Object-Oriented Programming in Python2-53 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.

55 Object-Oriented Programming in Python2-54 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.

56 Object-Oriented Programming in Python2-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

57 Object-Oriented Programming in Python2-56 Arithmetic Operators x + yaddition x - ysubtraction x * ymultiplication x / y"true" division x // y"integer" division x % ymodulo operator ("remainder") x ** yx raised to the power y abs(x)absolute value of x

58 Object-Oriented Programming in Python2-57 Comparison Operators x == yTrue if x equals y x != yTrue if x does not equal y x < yTrue if x strictly less than y x <= yTrue if x less than or equal to y x > yTrue if x strictly greather than y x >= yTrue if x greater than or equal to y cmp(x,y) Returns-1 if x < y 0 if x == y +1 if x > y

59 Object-Oriented Programming in Python2-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

60 Object-Oriented Programming in Python2-59 Immutable Objects >>> x = 5 >>> int 5 x

61 Object-Oriented Programming in Python2-60 Immutable Objects >>> x = 5 >>> x = x + 1 >>> int 6 x 5

62 Object-Oriented Programming in Python2-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'.

63 Object-Oriented Programming in Python2-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

64 Object-Oriented Programming in Python2-63 Type Conversions float(35) results in 35.0 str(35) results in '35' int( '35' ) results in 35 int( 'ten' ) results inan 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

65 Object-Oriented Programming in Python2-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

66 Object-Oriented Programming in Python2-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.

67 Object-Oriented Programming in Python2-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

68 Object-Oriented Programming in Python2-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

69 Object-Oriented Programming in Python2-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

70 Object-Oriented Programming in Python2-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

71 Object-Oriented Programming in Python2-70 Expressions 18 + 5 + 2 Multiple operations can be expressed at once + 5 18 () 23

72 Object-Oriented Programming in Python2-71 Expressions 23 + 5 18 23 25 Multiple operations can be expressed at once 2 +()+ 2

73 Object-Oriented Programming in Python2-72 Expressions 25 + 5 18 23 25 Multiple operations can be expressed at once 2 + ((18 + 5) + 2) addition is left-associative

74 Object-Oriented Programming in Python2-73 Precedence 1 + 2 * 3 Some operators are given precedence over others * 3 2 () + 1 ()

75 Object-Oriented Programming in Python2-74 Using Parentheses (1 + 2) * 3 You can control the evaluation by giving explicit parentheses in your expressions. + 2 1 * 3

76 Object-Oriented Programming in Python2-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

77 Object-Oriented Programming in Python2-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.

78 Object-Oriented Programming in Python2-77 Logical Operators x y not x x and yx or yx == yx != y False TrueFalse TrueFalse True FalseTrueFalseTrue False TrueFalseTrue FalseTrue False

79 Object-Oriented Programming in Python2-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

80 Object-Oriented Programming in Python2-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…

81 Object-Oriented Programming in Python2-80 Source Code >>> groceries = list( ) >>> groceries.append('bread') >>> groceries.append('milk') >>> groceries.append('cheese') Interpreter Session groceries = list( ) groceries.append('bread') groceries.append('milk') groceries.append('cheese') Source Code demo.py

82 Object-Oriented Programming in Python2-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 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

83 Object-Oriented Programming in Python2-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.

84 Object-Oriented Programming in Python2-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.

85 Object-Oriented Programming in Python2-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)

86 Object-Oriented Programming in Python2-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.

87 Object-Oriented Programming in Python2-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.

88 Object-Oriented Programming in Python2-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

89 Object-Oriented Programming in Python2-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: apple You picked apple

90 Object-Oriented Programming in Python2-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).

91 Object-Oriented Programming in Python2-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 list groceries = list( ) # it is initially empty

92 Object-Oriented Programming in Python2-91 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


Download ppt "Getting Started with Python Object-Oriented Programming in Python Goldwasser and Letscher Chapter 2."

Similar presentations


Ads by Google