getting started with python object-oriented programming in python goldwasser and letscher chapter 2

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

Post on 19-Dec-2015

264 views

Category:

Documents


2 download

TRANSCRIPT

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

Getting Started with Python

Object-Oriented Programming in PythonGoldwasser and Letscher

Chapter 2

Page 2: Getting Started with Python Object-Oriented Programming in Python Goldwasser 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

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

Object-Oriented Programming in Python 2-3

The Python Prompt

>>>

• This lets us know that the interpreter awaits our next command

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

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?

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

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

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

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

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

Object-Oriented Programming in Python 2-7

Calling a Method

>>> groceries = list()>>> groceries.append('bread')>>>

list

'bread'

groceries

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

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>>>

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

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

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

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?

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

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']

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

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']>>>

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

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)

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

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')>>>

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

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

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

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

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

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>>>

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

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

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

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__( )

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

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

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

Object-Oriented Programming in Python 2-21

>>> waitlist['Kim', 'Donald', 'Eric', 'Nell']>>>

Negative Indices

'Nell'>>>

waitlist[-1]

waitlist[-3]'Donald'>>> waitlist[-4]'Kim'>>>

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

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']

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

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

>>>

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

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]

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

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]

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

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

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

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)

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

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.

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

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?"

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

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'

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

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'

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

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'

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

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)

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

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)

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

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)

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

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)

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

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)

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

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)

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

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)

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

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)

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

Object-Oriented Programming in Python 2-41

Example: lower( )

>>> formal = 'Hello'>>>

str

'Hello'

formal

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

Object-Oriented Programming in Python 2-42

Example: lower( )

>>> formal = 'Hello'>>> informal = formal.lower()>>>

str

'hello'

informalstr

'Hello'

formal

Note that formal is unchanged

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

Object-Oriented Programming in Python 2-43

Reassigning an Identifier

>>> person = 'Alice'>>>

str

'Alice'

person

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

Object-Oriented Programming in Python 2-44

Reassigning an Identifier

>>> person = 'Alice'>>> person = person.lower()>>>

str

'alice'

personstr

'Alice'

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

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.

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

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

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

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.

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

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']

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

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)

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

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']

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

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'

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

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'

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

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.

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

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.

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

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

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

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

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

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

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

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

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

Object-Oriented Programming in Python 2-59

Immutable Objects

>>> x = 5>>>

int

5

x

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

Object-Oriented Programming in Python 2-60

Immutable Objects

>>> x = 5>>> x = x + 1>>>

int

6

xint

5

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

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'.

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

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

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

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

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

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

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

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.

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

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

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

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

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

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

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

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

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

Object-Oriented Programming in Python 2-70

Expressions

18 + 5 + 2

Multiple operations can be expressed at once

+

518

( )

23

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

Object-Oriented Programming in Python 2-71

Expressions

23

+

518

23

25

Multiple operations can be expressed at once

2

+( )+ 2

Page 72: Getting Started with Python Object-Oriented Programming in Python Goldwasser and Letscher Chapter 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

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

Object-Oriented Programming in Python 2-73

Precedence

1 + 2 * 3

Some operators are given precedence over others

*

32

( ) +

1

( )

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

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

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

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

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

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.

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

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

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

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

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

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…

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

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

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

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

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

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.

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

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.

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

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)

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

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.

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

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.

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

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

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

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

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

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).

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

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

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

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