0% found this document useful (0 votes)
7 views169 pages

After Mid

Uploaded by

aboodabogus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views169 pages

After Mid

Uploaded by

aboodabogus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 169

Starting out with Python

Fifth Edition, Global Edition

Chapter 7
Lists and Tuples

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-1


Topics (1 of 2)
• Sequences
• Introduction to Lists
• List Slicing
• Finding Items in Lists with the in Operator
• List Methods and Useful Built-in Functions

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-2


Topics (2 of 2)
• Copying Lists
• Processing Lists
• List Comprehensions
• Two-Dimensional Lists
• Tuples
• Plotting List Data with the matplotlib Package

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-3


Sequences
• Sequence: an object that contains multiple items of
data
– The items are stored in sequence one after another
• Python provides different types of sequences,
including lists and tuples
– The difference between these is that a list is mutable
and a tuple is immutable

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-4


Introduction to Lists (1 of 2)
• List: an object that contains multiple data items
– Element: An item in a list
– Format: list = [item1, item2, etc.]
– Can hold items of different types
• print function can be used to display an entire
list
• list() function can convert certain types of
objects to lists

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-5


Introduction to Lists (2 of 2)

Figure 7-1 A list of integers

Figure 7-2 A list of strings

Figure 7-3 A list holding different types

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-6


The Repetition Operator and Iterating
over a List
• Repetition operator: makes multiple copies of a list
and joins them together
– The * symbol is a repetition operator when applied to a
sequence and an integer
 Sequence is left operand, number is right
– General format: list * n
• You can iterate over a list using a for loop
– Format: for x in list:

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-7


Indexing
• Index: a number specifying the position of an element
in a list
– Enables access to individual element in list
– Index of first element in the list is 0, second element is
1, and n’th element is n-1
– Negative indexes identify positions relative to the end
of the list
 The index -1 identifies the last element, -2 identifies the
next to last element, etc.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-8


The len function
• An IndexError exception is raised if an invalid index
is used
• len function: returns the length of a sequence such
as a list
– Example: size = len(my_list)
– Returns the number of elements in the list, so the index
of last element is len(list)-1
– Can be used to prevent an IndexError exception
when iterating over a list with a loop

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7-9


Lists Are Mutable
• Mutable sequence: the items in the sequence can be
changed
– Lists are mutable, and so their elements can be
changed
• An expression such as
• list[1] = new_value can be used to assign a
new value to a list element
– Must use a valid index to prevent raising of an
IndexError exception

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 10


Concatenating Lists
• Concatenate: join two things together
• The + operator can be used to concatenate two lists
– Cannot concatenate a list with another data type, such
as a number
• The += augmented assignment operator can also be
used to concatenate lists

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 11


List Slicing
• Slice: a span of items that are taken from a sequence
– List slicing format: list[start : end]
– Span is a list containing copies of elements from
start up to, but not including, end
 If start not specified, 0 is used for start index
 If end not specified, len(list) is used for end index
– Slicing expressions can include a step value and
negative indexes relative to end of list

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 12


Finding Items in Lists with the in
Operator
• You can use the in operator to determine whether an
item is contained in a list
– General format: item in list
– Returns True if the item is in the list, or False if it is
not in the list
• Similarly you can use the not in operator to
determine whether an item is not in a list

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 13


List Methods and Useful Built-in
Functions (1 of 4)
• append(item): used to add items to a list – item is
appended to the end of the existing list
• index(item): used to determine where an item is
located in a list
– Returns the index of the first element in the list
containing item
– Raises ValueError exception if item not in the list

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 14


List Methods and Useful Built-in
Functions (2 of 4)
• insert(index, item): used to insert item at
position index in the list
• sort(): used to sort the elements of the list in
ascending order
• remove(item): removes the first occurrence of
item in the list
• reverse(): reverses the order of the elements in the
list

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 15


List Methods and Useful Built-in
Functions (3 of 4)
Table 7-1 A few of the list methods

Method Description
append(item) Adds item to the end of the list.

index(item) Returns the index of the first element whose value is equal to item.
A ValueError exception is raised if item is not found in the list.
insert(index, item) Inserts item into the list at the specified index. When an item is inserted into a
list, the list is expanded in size to accommodate the new item. The item that
was previously at the specified index, and all the items after it, are shifted by
one position toward the end of the list. No exceptions will occur if you specify
an invalid index. If you specify an index beyond the end of the list, the item will
be added to the end of the list. If you use a negative index that specifies an
invalid position, the item will be inserted at the beginning of the list.
sort() Sorts the items in the list so they appear in ascending order (from the lowest
value to the highest value).
remove(item) Removes the first occurrence of item from the list. A ValueError exception
is raised if item is not found in the list.
reverse() Reverses the order of the items in the list.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 16


List Methods and Useful Built-in
Functions (4 of 4)
• del statement: removes an element from a specific
index in a list
– General format: del list[i]
• min and max functions: built-in functions that
returns the item that has the lowest or highest value in
a sequence
– The sequence is passed as an argument

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 17


Copying Lists (1 of 2)
• To make a copy of a list you must copy each element
of the list
– Two methods to do this:
 Creating a new empty list and using a for loop to add a
copy of each element from the original list to the new list
 Creating a new empty list and concatenating the old list
to the new empty list

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 18


Copying Lists (2 of 2)

Figure 7-5 list1 and list2 reference the same list

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 19


Processing Lists (1 of 2)
• List elements can be used in calculations
• To calculate total of numeric values in a list use loop
with accumulator variable
• To average numeric values in a list:
– Calculate total of the values
– Divide total of the values by len(list)
• List can be passed as an argument to a function

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 20


Processing Lists (2 of 2)
• A function can return a reference to a list
• To save the contents of a list to a file:
– Use the file object’s writelines method
 Does not automatically write \n at then end of each item
– Use a for loop to write each element and \n
• To read data from a file use the file object’s
readlines method

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 21


List Comprehensions (1 of 7)
• List comprehension: a concise expression that creates
a new list by iterating over the elements of an existing
list.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 22


List Comprehensions (2 of 7)
• The following code uses a for loop to make a copy of
a list:
list1 = [1, 2, 3, 4]
list2 = []

for item in list1:


list2.append(item)

• The following code uses a list comprehension to make


a copy of a list:
list1 = [1, 2, 3, 4]
list2 = [item for item in list1]

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 23


List Comprehensions (3 of 7)

• The iteration expression works like a for loop


• In this example, it iterates over the elements of list1
• Each time it iterates, the target variable item is assigned
the value of an element.
• At the end of each iteration, the value of the result
expression is appended to the new list.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 24


List Comprehensions (4 of 7)

list1 = [1, 2, 3, 4]
list2 = [item**2 for item in list1]

• After this code executes, list2 will contain the values


[1, 4, 9, 16]

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 25


List Comprehensions (5 of 7)

str_list = ['Winken', 'Blinken', 'Nod']


len_list = [len(s) for s in str_list]

• After this code executes, len_list will contain the


values [6, 7, 3]

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 26


List Comprehensions (6 of 7)
• You can use an if clause in a list comprehension to select
only certain elements when processing a list
list1 = [1, 12, 2, 20, 3, 15, 4]
list2 = []

for n in list1:
if n < 10:
list2.append(n)

Works the same as…

list1 = [1, 12, 2, 20, 3, 15, 4]


list2 = [item for item in list1 if item < 10]

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 27


List Comprehensions (7 of 7)

list1 = [1, 12, 2, 20, 3, 15, 4]


list2 = [item for item in list1 if item < 10]

• After this code executes, list2 will contain [1, 2, 3, 4]

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 28


Two-Dimensional Lists (1 of 3)
• Two-dimensional list: a list that contains other lists as
its elements
– Also known as nested list
– Common to think of two-dimensional lists as having
rows and columns
– Useful for working with multiple sets of data
• To process data in a two-dimensional list need to use
two indexes
• Typically use nested loops to process

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 29


Two-Dimensional Lists (2 of 3)

Figure 7-8 A two-dimensional list

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 30


Two-Dimensional Lists (3 of 3)

Figure 7-10 Subscripts for each element of the scores list

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 31


Tuples (1 of 3)
• Tuple: an immutable sequence
– Very similar to a list
– Once it is created it cannot be changed
– Format: tuple_name = (item1, item2)
– Tuples support operations as lists
 Subscript indexing for retrieving elements
 Methods such as index
 Built in functions such as len, min, max
 Slicing expressions
 The in, +, and * operators

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 32


Tuples (2 of 3)
• Tuples do not support the methods:
– append
– remove
– insert
– reverse
– sort

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 33


Tuples (3 of 3)
• Advantages for using tuples over lists:
– Processing tuples is faster than processing lists
– Tuples are safe
– Some operations in Python require use of tuples
• list() function: converts tuple to list
• tuple() function: converts list to tuple

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 34


Plotting Data with matplotlib (1 of 4)
• The matplotlib package is a library for creating
two-dimensional charts and graphs.
• It is not part of the standard Python library, so you will
have to install it separately, after you have installed
Python on your system.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 35


Plotting Data with matplotlib (2 of 4)
• To install matplotlib on a Windows system, open a
Command Prompt window and enter this command:
pip install matplotlib

• To install matplotlib on a Mac or Linux system,


open a Terminal window and enter this command:
sudo pip3 install matplotlib

• See Appendix F in your textbook for more information


about packages and the pip utility.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 36


Plotting Data with matplotlib (3 of 4)
• To verify the package was installed, start IDLE and
enter this command:

>>> import matplotlib

• If you don't see any error messages, you can assume


the package was properly installed.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 37


Plotting Data with matplotlib (4 of 4)
• The matplotlib package contains a module named
pyplot that you will need to import.
• Use the following import statement to import the
module and create an alias named plt:

import matplotlib.pyplot as plt

For more information about the import statement, see Appendix E in your textbook.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 38


Plotting a Line Graph with the plot
Function (1 of 4)
• Use the plot function to create a line graph that connects
a series of points with straight lines.
• The line graph has a horizontal X axis, and a vertical Y
axis.
• Each point in the graph is located at a (X,Y) coordinate.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 39


Plotting a Line Graph with the plot
Function (2 of 4)
Program 7-20 (line_graph1.py)
1 # This program displays a simple line graph.
2 import matplotlib.pyplot as plt
3
4 def main():
5 # Create lists with the X and Y coordinates of each data
point.
6 x_coords = [0, 1, 2, 3, 4]
7 y_coords = [0, 3, 1, 5, 2]
8
9 # Build the line graph.
10 plt.plot(x_coords, y_coords)
11
12 # Display the line graph.
13 plt.show()
14
15 # Call the main function.
16 if _ _name_ _ == '_ _main_ _':
17 main()
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 40
Plotting a Line Graph with the plot
Function (3 of 4)
• You can change the lower and upper limits of the X
and Y axes by calling the xlim and ylim functions.
Example:
plt.xlim(xmin=1, xmax=100)
plt.ylim(ymin=10, ymax=50)

• This code does the following:


– Causes the X axis to begin at 1 and end at 100
– Causes the Y axis to begin at 10 and end at 50

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 41


Plotting a Line Graph with the plot
Function (4 of 4)
• You can customize each tick mark’s label with the
xticks and yticks functions.
• These functions each take two lists as arguments.
– The first argument is a list of tick mark locations
– The second argument is a list of labels to display at the
specified locations.
plt.xticks([0, 1, 2, 3, 4],
['2016', '2017', '2018', '2019', '2020'])
plt.yticks([0, 1, 2, 3, 4, 5],
['$0m', '$1m', '$2m', '$3m', '$4m', '$5m'])

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 42


Program 7-20
1 # This program displays a simple line graph.
2 import matplotlib.pyplot as plt
3
4 def main():
5 # Create lists with the X,Y coordinates of each data point.
6 x_coords = [0, 1, 2, 3, 4]
7 y_coords = [0, 3, 1, 5, 2]
8
9 # Build the line graph.
10 plt.plot(x_coords, y_coords, marker='o')
11
12 # Add a title.
13 plt.title('Sales by Year')
14
15 # Add labels to the axes.
16 plt.xlabel('Year')
17 plt.ylabel('Sales')
18
Continued. . .

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 43


Program 7-24
19 # Customize the tick marks.
20 plt.xticks([0, 1, 2, 3, 4],
21 ['2016', '2017', '2018', '2019', '2020'])
22 plt.yticks([0, 1, 2, 3, 4, 5],
23 ['$0m', '$1m', '$2m', '$3m', '$4m', '$5m'])
24
25 # Add a grid.
26 plt.grid(True)
27
28 # Display the line graph.
29 plt.show()
30
31 # Call the main function.
32 if __name__ == '__main__':
33 main()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 44


Output of Program 7-24
Displayed by the
Displayed by the
title() function.
yticks() function.

Displayed by the
ylabel() function.

Displayed by the
xticks() function. Displayed by the
xlabel() function.
Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 45
Plotting a Bar Chart (1 of 6)
• Use the bar function in the matplotlib.pyplot
module to create a bar chart.
• The function needs two lists: one with the X
coordinates of each bar’s left edge, and another with
the heights of each bar, along the Y axis.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 46


Plotting a Bar Chart (2 of 6)
left_edges = [0, 10, 20, 30, 40]
heights = [100, 200, 300, 400, 500]

plt.bar(left_edges, heights)
plt.show()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 47


Plotting a Bar Chart (3 of 6)
• The default width of each bar in a bar graph is 0.8
along the X axis.
• You can change the bar width by passing a third
argument to the bar function.
left_edges = [0, 10, 20, 30, 40]
heights = [100, 200, 300, 400, 500]
bar_width = 5

plt.bar(left_edges, heights, bar_width)


plt.show()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 48


Plotting a Bar Chart (4 of 6)
• The bar function has a color parameter that you
can use to change the colors of the bars.
• The argument that you pass into this parameter is a
tuple containing a series of color codes.

Color Code Corresponding Color


'b' Blue
'g' Green
'r' Red
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 49


Plotting a Bar Chart (5 of 6)
• Example of how to pass a tuple of color codes as a
keyword argument:
plt.bar(left_edges, heights, color=('r', 'g', 'b', 'w', 'k'))

• The colors of the bars in the resulting bar chart will be


as follows:
– The first bar will be red.
– The second bar will be green.
– The third bar will be blue.
– The fourth bar will be white.
– The fifth bar will be black.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 50


Plotting a Bar Chart (6 of 6)
• Use the xlabel and ylabel functions to add labels to the
X and Y axes.
• Use the xticks function to display custom tick mark
labels along the X axis
• Use the yticks function to display custom tick mark
labels along the Y axis.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 51


Plotting a Pie Chart (1 of 4)
• You use the pie function in the
matplotlib.pyplot module to create a pie chart.
• When you call the pie function, you pass a list of
values as an argument.
– The sum of the values will be used as the value of the
whole.
– Each element in the list will become a slice in the pie
chart.
– The size of a slice represents that element's value as a
percentage of the whole.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 52


Plotting a Pie Chart (2 of 4)
• Example

values = [20, 60, 80, 40]


plt.pie(values)
plt.show()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 53


Plotting a Pie Chart (3 of 4)
• The pie function has a labels parameter that you
can use to display labels for the slices in the pie chart.
• The argument that you pass into this parameter is a
list containing the desired labels, as strings.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 54


Plotting a Pie Chart (4 of 4)
• Example
sales = [100, 400, 300, 600]
slice_labels = ['1st Qtr', '2nd Qtr', '3rd Qtr', '4th Qtr']
plt.pie(sales, labels=slice_labels)
plt.title('Sales by Quarter')
plt.show()

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 55


Plotting a Pie Chart
• The pie function automatically changes the color of the
slices, in the following order:
– blue, green, red, cyan, magenta, yellow, black, and white.
• You can specify a different set of colors, however, by
passing a tuple of color codes as an argument to the pie
function’s colors parameter:
plt.pie(values, colors=('r', 'g', 'b', 'w', 'k'))

• When this statement executes, the colors of the slices in


the resulting pie chart will be red, green, blue, white, and
black.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 56


Summary
• This chapter covered:
– Lists, including:
 Repetition and concatenation operators
 Indexing
 Techniques for processing lists
 Slicing and copying lists
 List methods and built-in functions for lists
 Two-dimensional lists
– Tuples, including:
 Immutability
 Difference from and advantages over lists
– Plotting charts and graphs with the matplotlib Package

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 7 - 57


Starting out with Python
Fifth Edition, Global Edition

Chapter 8
More About Strings

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8-1


Topics
• Basic String Operations
• String Slicing
• Testing, Searching, and Manipulating Strings

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8-2


Basic String Operations
• Many types of programs perform operations on strings
• In Python, many tools for examining and manipulating
strings
– Strings are sequences, so many of the tools that work
with sequences work with strings

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8-3


Accessing the Individual Characters in
a String (1 of 4)
• To access an individual character in a string:
– Use a for loop
 Format: for character in string:
 Useful when need to iterate over the whole string, such
as to count the occurrences of a specific character
– Use indexing
 Each character has an index specifying its position in the
string, starting at 0
 Format: character = my_string[i]

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8-4


Accessing the Individual Characters in
a String (2 of 4)

Figure 8-1 Iterating over the string 'Juliet'

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8-5


Accessing the Individual Characters in
a String (3 of 4)

Figure 8-2 String indexes

Figure 8-3 Getting a copy of a character from a string

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8-6


Accessing the Individual Characters in
a String (4 of 4)
• IndexError exception will occur if:
– You try to use an index that is out of range for the string
 Likely to happen when loop iterates beyond the end of
the string
• len(string) function can be used to obtain the
length of a string
– Useful to prevent loops from iterating beyond the end
of a string

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8-7


String Concatenation
• Concatenation: appending one string to the end of
another string
– Use the + operator to produce a string that is a
combination of its operands
– The augmented assignment operator += can also be
used to concatenate strings
 The operand on the left side of the += operator must be
an existing variable; otherwise, an exception is raised

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8-8


Strings Are Immutable (1 of 2)
• Strings are immutable
– Once they are created, they cannot be changed
 Concatenation doesn’t actually change the existing
string, but rather creates a new string and assigns the
new string to the previously used variable
– Cannot use an expression of the form
– string[index] = new_character
 Statement of this type will raise an exception

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8-9


Strings Are Immutable (2 of 2)

Figure 8-4 The string ‘Carmen’ assigned to name

Figure 8-5 The string ‘Carmen Brown’ assigned to name

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 10


String Slicing
• Slice: span of items taken from a sequence, known as
substring
– Slicing format: string[start : end]
 Expression will return a string containing a copy of the
characters from start up to, but not including, end
 If start not specified, 0 is used for start index
 If end not specified, len(string) is used for end index
– Slicing expressions can include a step value and
negative indexes relative to end of string

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 11


Testing, Searching, and Manipulating
Strings
• You can use the in operator to determine whether
one string is contained in another string
– General format: string1 in string2
 string1 and string2 can be string literals or
variables referencing strings
• Similarly you can use the not in operator to
determine whether one string is not contained in
another string

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 12


String Methods (1 of 7)
• Strings in Python have many types of methods,
divided into different types of operations
– General format:
mystring.method(arguments)
• Some methods test a string for specific characteristics
– Generally Boolean methods, that return True if a
condition exists, and False otherwise

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 13


String Methods (2 of 7)
Table 8-1 Some string testing methods

Method Description
isalnum() Returns true if the string contains only alphabetic letters or digits and is at least one
character in length. Returns false otherwise.
isalpha() Returns true if the string contains only alphabetic letters and is at least one
character in length. Returns false otherwise.
isdigit() Returns true if the string contains only numeric digits and is at least one character
in length. Returns false otherwise.
islower() Returns true if all of the alphabetic letters in the string are lowercase, and the string
contains at least one alphabetic letter. Returns false otherwise.
isspace() Returns true if the string contains only whitespace characters and is at least one
character in length. Returns false otherwise. (Whitespace characters are spaces,
newlines (\n), and tabs (\t).
isupper() Returns true if all of the alphabetic letters in the string are uppercase, and the string
contains at least one alphabetic letter. Returns false otherwise.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 14


String Methods (3 of 7)
• Some methods return a copy of the string, to which
modifications have been made
– Simulate strings as mutable objects
• String comparisons are case-sensitive
– Uppercase characters are distinguished from
lowercase characters
– lower and upper methods can be used for making
case-insensitive string comparisons

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 15


String Methods (4 of 7)
Table 8-2 String Modification Methods

Method Description
lower() Returns a copy of the string with all alphabetic letters converted to lowercase. Any
character that is already lowercase, or is not an alphabetic letter, is unchanged.
lstrip() Returns a copy of the string with all leading whitespace characters removed. Leading
whitespace characters are spaces, newlines (\n), and tabs (\t) that appear at the
beginning of the string.
lstrip(char) The char argument is a string containing a character. Returns a copy of the string with all
instances of char that appear at the beginning of the string removed.
rstrip() Returns a copy of the string with all trailing whitespace characters removed. Trailing
whitespace characters are spaces, newlines (\n), and tabs (\t) that appear at the end of
the string.
rstrip(char) The char argument is a string containing a character. The method returns a copy of the
string with all instances of char that appear at the end of the string removed.
strip() Returns a copy of the string with all leading and trailing whitespace characters removed.
strip(char) Returns a copy of the string with all instances of char that appear at the beginning and
the end of the string removed.
upper() Returns a copy of the string with all alphabetic letters converted to uppercase. Any
character that is already uppercase, or is not an alphabetic letter, is unchanged.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 16


String Methods (5 of 7)
• Programs commonly need to search for substrings
• Several methods to accomplish this:
– endswith(substring): checks if the string ends
with substring
 Returns True or False
– startswith(substring): checks if the string starts
with substring
 Returns True or False

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 17


String Methods (6 of 7)
• Several methods to accomplish this (cont’d):
– find(substring): searches for substring within
the string
 Returns lowest index of the substring, or if the substring
is not contained in the string, returns -1
– replace(substring, new_string):
 Returns a copy of the string where every occurrence of
substring is replaced with new_string

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 18


String Methods (7 of 7)

Table 8-3 Search and replace methods

Method Description
endswith(substring) The substring argument is a string. The method returns true if the
string ends with substring.
find(substring) The substring argument is a string. The method returns the
lowest index in the string where substring is found. If substring
is not found, the method returns −1.
replace(old, new) The old and new arguments are both strings. The method returns a
copy of the string with all instances of old replaced by new.
startswith(substring) The substring argument is a string. The method returns true if the
string starts with substring.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 19


The Repetition Operator
• Repetition operator: makes multiple copies of a string
and joins them together
– The * symbol is a repetition operator when applied to a
string and an integer
 String is left operand; number is right
– General format: string_to_copy * n
– Variable references a new string which contains
multiple copies of the original string

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 20


Splitting a String (1 of 2)
• split method: returns a list containing the words in
the string
– By default, uses space as separator
– Can specify a different separator by passing it as an
argument to the split method

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 21


Splitting a String (2 of 2)
• Examples:
>>> my_string = 'One two three four'
>>> word_list = my_string.split()
>>> word_list
['One', 'two', 'three', 'four']
>>>

>>> my_string = '1/2/3/4/5'


>>> number_list = my_string.split('/')
>>> number_list
['1', '2', '3', '4', '5']
>>>

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 22


String Tokens (1 of 4)
• Sometimes a string contains substrings that are
separated by a special character
– Example:
'peach raspberry strawberry vanilla'
– This string contains the substrings peach, raspberry,
strawberry, and vanilla
– The substrings are separated by the space character
– The substrings are known as tokens and the
separating character is known as the delimiter

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 23


String Tokens (2 of 4)
• Example:
'17;92;81;12;46;5'

– This string contains the tokens 17, 92, 81, 12, 46, and 5
– The delimiter is the ; character

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 24


String Tokens (3 of 4)
• Tokenizing is the process of breaking a string into
tokens
• When you tokenize a string, you extract the tokens
and store them as individual items
• In Python you can use the split method to tokenize a
string

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 25


String Tokens (4 of 4)
• Examples:
>>> str = 'peach raspberry strawberry vanilla'
>>> tokens = str.split()
>>> tokens
['peach', 'raspberry', 'strawberry', 'vanilla']
>>>

>>> my_address = 'www.example.com'


>>> tokens = my_address.split('.')
>>> tokens
['www', 'example', 'com']
>>>

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 26


Summary
• This chapter covered:
– String operations, including:
 Methods for iterating over strings
 Repetition and concatenation operators
 Strings as immutable objects
 Slicing strings and testing strings
 String methods
 Splitting a string

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 8 - 27


Starting out with Python
Fifth Edition, Global Edition

Chapter 9
Dictionaries and Sets

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9-1


Topics
• Dictionaries
• Sets
• Serializing Objects

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9-2


Dictionaries
• Dictionary: object that stores a collection of data
– Each element consists of a key and a value
 Often referred to as mapping of key to value
 Key must be an immutable object
– To retrieve a specific value, use the key associated
with it
– Format for creating a dictionary
dictionary =
{key1:val1, key2:val2}

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9-3


Retrieving a Value from a Dictionary
• Elements in dictionary are unsorted
• General format for retrieving value from dictionary:
dictionary[key]
– If key in the dictionary, associated value is returned,
otherwise, KeyError exception is raised
• Test whether a key is in a dictionary using the in and
not in operators
– Helps prevent KeyError exceptions

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9-4


Adding Elements to an Existing
Dictionary
• Dictionaries are mutable objects
• To add a new key-value pair:
dictionary[key] = value
– If key exists in the dictionary, the value associated with
it will be changed

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9-5


Deleting Elements From an Existing
Dictionary
• To delete a key-value pair:
del dictionary[key]
– If key is not in the dictionary, KeyError exception is
raised

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9-6


Getting the Number of Elements and
Mixing Data Types
• len function: used to obtain number of elements in a
dictionary
• Keys must be immutable objects, but associated
values can be any type of object
– One dictionary can include keys of several different
immutable types
• Values stored in a single dictionary can be of different
types

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9-7


Creating an Empty Dictionary and Using
for Loop to Iterate Over a Dictionary
• To create an empty dictionary:
– Use {}
– Use built-in function dict()
– Elements can be added to the dictionary as program
executes
• Use a for loop to iterate over a dictionary
– General format: for key in dictionary:

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9-8


Some Dictionary Methods (1 of 5)
• clear method: deletes all the elements in a
dictionary, leaving it empty
– Format: dictionary.clear()
• get method: gets a value associated with specified
key from the dictionary
– Format: dictionary.get(key, default)
 default is returned if key is not found
– Alternative to [] operator
 Cannot raise KeyError exception

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9-9


Some Dictionary Methods (2 of 5)
• items method: returns all the dictionaries keys and
associated values
– Format: dictionary.items()
– Returned as a dictionary view
 Each element in dictionary view is a tuple which contains
a key and its associated value
 Use a for loop to iterate over the tuples in the sequence
– Can use a variable which receives a tuple, or can use two
variables which receive key and value

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 10


Some Dictionary Methods (3 of 5)
• keys method: returns all the dictionaries keys as a
sequence
– Format: dictionary.keys()
• pop method: returns value associated with specified
key and removes that key-value pair from the
dictionary
– Format: dictionary.pop(key, default)
 default is returned if key is not found

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 11


Some Dictionary Methods (4 of 5)
• popitem method: Returns, as a tuple, the key-value
pair that was last added to the dictionary. The method
also removes the key-value pair from the dictionary.
– Format: dictionary.popitem()
– Key-value pair returned as a tuple
• values method: returns all the dictionaries values as
a sequence
– Format: dictionary.values()
– Use a for loop to iterate over the values

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 12


Some Dictionary Methods (5 of 5)
Table 9-1 Some of the dictionary methods

Method Description
Clear Clears the contents of a dictionary.
get Gets the value associated with a specified key. If the key is not found, the method
does not raise an exception. Instead, it returns a default value.
items Returns all the keys in a dictionary and their associated values as a sequence of
tuples.
keys Returns all the keys in a dictionary as a sequence of tuples.
pop Returns the value associated with a specified key and removes that key-value pair
from the dictionary. If the key is not found, the method returns a default value.
popitem Returns, as a tuple, the key-value pair that was last added to the dictionary. The
method also removes the key-value pair from the dictionary.
values Returns all the values in the dictionary as a sequence of tuples.

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 13


Dictionary Comprehensions (1 of 6)
• Dictionary comprehension: an expression that reads a
sequence of input elements and uses those input
elements to produce a dictionary

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 14


Dictionary Comprehensions (2 of 6)
• Example: create a dictionary in which the keys are the
integers 1 through 4 and the values are the squares of the
keys >>> numbers = [1, 2, 3, 4]
Using a for >>> squares = {}
>>> for item in numbers:
loop
... squares[item] = item**2
...
>>> squares
{1: 1, 2: 4, 3: 9, 4: 16}
>>>

Using a >>> squares = {item:item**2 for item in


dictionary numbers}
comprehension >>> squares
{1: 1, 2: 4, 3: 9, 4: 16}
>>>

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 15


Dictionary Comprehensions (3 of 6)

squares = {item:item**2 for item in numbers}

Result Expression Iteration Expression

• The iteration expression iterates over the elements of numbers


• Each time it iterates, the target variable item is assigned the value
of an element
• At the end of each iteration, an element containing item as the key
and item**2 as the value is added to the new dictionary

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 16


Dictionary Comprehensions (4 of 6)
• Example: You have an existing list of strings. Create a
dictionary in which the keys are the stings in the list,
and the values are the lengths of the strings

>>> names = ['Jeremy', 'Kate', 'Peg']


>>> str_lengths = {item:len(item) for item in names}
>>> str_lengths
{'Jeremy': 6, 'Kate': 4, 'Peg': 3}
>>>

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 17


Dictionary Comprehensions (5 of 6)
• Example: making a copy of a dictionary

>>> dict1 = {'A':1, 'B':2, 'C':3}


>>> dict2 = {k:v for k,v in dict1.items()}
>>> dict2
{'A': 1, 'B': 2, 'C': 3}
>>>

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 18


Dictionary Comprehensions (6 of 6)
• You can use an if clause in a dictionary
comprehension to select only certain elements of the
input sequence
– Example: A dictionary contains cities and their populations
as key-value pairs. Select only the cities with a population
greater than 2 million
>>> populations = {'New York': 8398748, 'Los Angeles': 3990456,
... 'Chicago': 2705994, 'Houston': 2325502,
... 'Phoenix': 1660272, 'Philadelphia': 1584138}
>>> largest = {k:v for k,v in populations.items() if v > 2000000}
>>> largest
{'New York': 8398748, 'Los Angeles': 3990456, 'Chicago': 2705994,
'Houston': 2325502}
>>>

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 19


Sets
• Set: object that stores a collection of data in same
way as mathematical set
– All items must be unique
– Set is unordered
– Elements can be of different data types

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 20


Creating a Set
• set function: used to create a set
– For empty set, call set()
– For non-empty set, call set(argument) where
argument is an object that contains iterable elements
 e.g., argument can be a list, string, or tuple
 If argument is a string, each character becomes a set
element
– For set of strings, pass them to the function as a list
 If argument contains duplicates, only one of the
duplicates will appear in the set

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 21


Getting the Number of and Adding
Elements
• len function: returns the number of elements in the
set
• Sets are mutable objects
• add method: adds an element to a set
• update method: adds a group of elements to a set
– Argument must be a sequence containing iterable
elements, and each of the elements is added to the set

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 22


Deleting Elements From a Set
• remove and discard methods: remove the specified
item from the set
– The item that should be removed is passed to both
methods as an argument
– Behave differently when the specified item is not found
in the set
 remove method raises a KeyError exception
 discard method does not raise an exception

• clear method: clears all the elements of the set

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 23


Using the for Loop, in, and not in
Operators With a Set
• A for loop can be used to iterate over elements in a
set
– General format: for item in set:
– The loop iterates once for each element in the set
• The in operator can be used to test whether a value
exists in a set
– Similarly, the not in operator can be used to test
whether a value does not exist in a set

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 24


Finding the Union of Sets
• Union of two sets: a set that contains all the elements
of both sets
• To find the union of two sets:
– Use the union method
 Format: set1.union(set2)
– Use the | operator
 Format: set1 | set2
– Both techniques return a new set which contains the
union of both sets

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 25


Finding the Intersection of Sets
• Intersection of two sets: a set that contains only the
elements found in both sets
• To find the intersection of two sets:
– Use the intersection method
 Format: set1.intersection(set2)
– Use the & operator
 Format: set1 & set2
– Both techniques return a new set which contains the
intersection of both sets

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 26


Finding the Difference of Sets
• Difference of two sets: a set that contains the
elements that appear in the first set but do not appear
in the second set
• To find the difference of two sets:
– Use the difference method
 Format: set1.difference(set2)
– Use the - operator
 Format: set1 - set2

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 27


Finding the Symmetric Difference of
Sets
• Symmetric difference of two sets: a set that contains
the elements that are not shared by the two sets
• To find the symmetric difference of two sets:
– Use the symmetric_difference method
 Format: set1.symmetric_difference(set2)
– Use the ^ operator
 Format: set1 ^ set2

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 28


Finding Subsets and Supersets (1 of 2)
• Set A is subset of set B if all the elements in set A are
included in set B
• To determine whether set A is subset of set B
– Use the issubset method
 Format: setA.issubset(setB)
– Use the <= operator
 Format: setA <= setB

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 29


Finding Subsets and Supersets (2 of 2)
• Set A is superset of set B if it contains all the elements
of set B
• To determine whether set A is superset of set B
– Use the issuperset method
 Format: setA.issuperset(setB)
– Use the >= operator
 Format: setA >= setB

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 30


Set Comprehensions (1 of 4)
• Set comprehension: a concise expression that creates
a new set by iterating over the elements of a
sequence
• Set comprehensions are written just like list
comprehensions, except that a set comprehension is
enclosed in curly braces ({}) instead of brackets ([])

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 31


Set Comprehensions (2 of 4)
• Example: making a copy of a set

>>> set1 = set([1, 2, 3, 4, 5])


>>> set2 = {item for item in set1}
>>> set2
{1, 2, 3, 4, 5}
>>>

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 32


Set Comprehensions (3 of 4)
• Example: creating a set that contains the squares of
the numbers stored in another set

>>> set1 = set([1, 2, 3, 4, 5])


>>> set2 = {item**2 for item in set1}
>>> set2
{1, 4, 9, 16, 25}
>>>

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 33


Set Comprehensions (4 of 4)
• Example: copying the numbers in a set that are less
than 10
>>> set1 = set([1, 20, 2, 40, 3, 50])
>>> set2 = {item for item in set1 if item < 10}
>>> set2
{1, 2, 3}
>>>

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 34


Serializing Objects (1 of 3)
• Serialize an object: convert the object to a stream of
bytes that can easily be stored in a file
• Pickling: serializing an object

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 35


Serializing Objects (2 of 3)
• To pickle an object:
– Import the pickle module
– Open a file for binary writing
– Call the pickle.dump function
 Format: pickle.dump(object, file)
– Close the file
• You can pickle multiple objects to one file prior to
closing the file

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 36


Serializing Objects (3 of 3)
• Unpickling: retrieving pickled object
• To unpickle an object:
– Import the pickle module
– Open a file for binary writing
– Call the pickle.load function
 Format: pickle.load(file)
– Close the file
• You can unpickle multiple objects from the file

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 37


Summary (1 of 2)
• This chapter covered:
– Dictionaries, including:
 Creating dictionaries
 Inserting, retrieving, adding, and deleting key-value pairs
 for loops and in and not in operators
 Dictionary methods

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 38


Summary (2 of 2)
• This chapter covered (cont’d):
– Sets:
 Creating sets
 Adding elements to and removing elements from sets
 Finding set union, intersection, difference and symmetric
difference
 Finding subsets and supersets
– Serializing objects
 Pickling and unpickling objects

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 9 - 39


Starting out with Python
Fifth Edition, Global Edition

Chapter 10
Classes and Object-Oriented
Programming

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 1


Topics
• Procedural and Object-Oriented Programming
• Classes
• Working with Instances
• Techniques for Designing Classes

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 2


Procedural Programming
• Procedural programming: writing programs made of
functions that perform specific tasks
– Procedures typically operate on data items that are
separate from the procedures
– Data items commonly passed from one procedure to
another
– Focus: to create procedures that operate on the
program’s data

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 3


Object-Oriented Programming (1 of 4)
• Object-oriented programming: focused on creating
objects
• Object: entity that contains data and procedures
– Data is known as data attributes and procedures are
known as methods
 Methods perform operations on the data attributes

• Encapsulation: combining data and code into a single


object

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 4


Object-Oriented Programming (2 of 4)

Figure 10-1 An object contains data attributes and methods

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 5


Object-Oriented Programming (3 of 4)
• Data hiding: object’s data attributes are hidden from
code outside the object
– Access restricted to the object’s methods
 Protects from accidental corruption
 Outside code does not need to know internal structure of
the object

• Object reusability: the same object can be used in


different programs
– Example: 3D image object can be used for architecture
and game programming

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 6


Object-Oriented Programming (4 of 4)

Figure 10-2 Code outside the object interacts with the object’s methods

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 7


An Everyday Example of an Object
• Data attributes: define the state of an object
– Example: clock object would have second, minute,
and hour data attributes
• Public methods: allow external code to manipulate the
object
– Example: set_time, set_alarm_time
• Private methods: used for object’s inner workings

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 8


Classes (1 of 3)
• Class: code that specifies the data attributes and
methods of a particular type of object
– Similar to a blueprint of a house or a cookie cutter
• Instance: an object created from a class
– Similar to a specific house built according to the
blueprint or a specific cookie
– There can be many instances of one class

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 9


Classes (2 of 3)

Figure 10-3 A blueprint and houses built from the blueprint

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 10


Classes (3 of 3)

Figure 10-4 The housefly and mosquito objects are instances of the Insect class

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 11


Class Definitions (1 of 4)
• Class definition: set of statements that define a class’s
methods and data attributes
– Format: begin with class Class_name:
 Class names often start with uppercase letter
– Method definition like any other python function
definition
 self parameter: required in every method in the class –
references the specific object that the method is working
on

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 12


Class Definitions (2 of 4)
• Initializer method: automatically executed when an
instance of the class is created
– Initializes object’s data attributes and assigns self
parameter to the object that was just created
– Format: def __init__ (self):
– Usually the first method in a class definition

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 13


Class Definitions (3 of 4)

Figure 10-5 Actions caused by the Coin() expression

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 14


Class Definitions (4 of 4)
• To create a new instance of a class call the initializer
method
– Format: My_instance = Class_Name()
• To call any of the class methods using the created
instance, use dot notation
– Format: My_instance.method()
– Because the self parameter references the specific
instance of the object, the method will affect this
instance
 Reference to self is passed automatically

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 15


Hiding Attributes and Storing Classes
in Modules
• An object’s data attributes should be private
– To make sure of this, place two underscores (__) in
front of attribute name
 Example: __current_minute

• Classes can be stored in modules


– Filename for module must end in .py
– Module can be imported to programs that use the class

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 16


The BankAccount Class – More About
Classes
• Class methods can have multiple parameters in
addition to self
– For __init__, parameters needed to create an
instance of the class
 Example: a BankAccount object is created with a
balance
– When called, the initializer method receives a value to be
assigned to a __balance attribute
– For other methods, parameters needed to perform
required task
 Example: deposit method amount to be deposited

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 17


The __str__ method
• Object’s state: the values of the object’s attribute at a
given moment
• __str__ method: displays the object’s state
– Automatically called when the object is passed as an
argument to the print function
– Automatically called when the object is passed as an
argument to the str function

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 18


Working With Instances (1 of 3)
• Instance attribute: belongs to a specific instance of a
class
– Created when a method uses the self parameter to
create an attribute
• If many instances of a class are created, each would
have its own set of attributes

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 19


Working With Instances (2 of 3)

Figure 10-7 The coin1, coin2, and coin3 variables reference three Coin objects

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 20


Working With Instances (3 of 3)

Figure 10-8 The objects after the toss method

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 21


Accessor and Mutator Methods
• Typically, all of a class’s data attributes are private and
provide methods to access and change them
• Accessor methods: return a value from a class’s
attribute without changing it
– Safe way for code outside the class to retrieve the
value of attributes
• Mutator methods: store or change the value of a data
attribute

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 22


Passing Objects as Arguments
• Methods and functions often need to accept objects
as arguments
• When you pass an object as an argument, you are
actually passing a reference to the object
– The receiving method or function has access to the
actual object
 Methods of the object can be called within the receiving
function or method, and data attributes may be changed
using mutator methods

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 23


Techniques for Designing Classes (1 of 3)
• UML diagram: standard diagrams for graphically
depicting object-oriented systems
– Stands for Unified Modeling Language
• General layout: box divided into three sections:
– Top section: name of the class
– Middle section: list of data attributes
– Bottom section: list of class methods

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 24


Techniques for Designing Classes (2 of 3)

Figure 10-9 General layout of a UML diagram for a class

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 25


Techniques for Designing Classes (3 of 3)

Figure 10-10 UML diagram for the Coin class

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 26


Finding the Classes in a Problem (1 of 4)
• When developing object oriented program, first goal is
to identify classes
– Typically involves identifying the real-world objects that
are in the problem
– Technique for identifying classes:
1. Get written description of the problem domain
2. Identify all nouns in the description, each of which is a
potential class
3. Refine the list to include only classes that are relevant
to the problem

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 27


Finding the Classes in a Problem (2 of 4)
1. Get written description of the problem domain
– May be written by you or by an expert
– Should include any or all of the following:
 Physical objects simulated by the program
 The role played by a person
 The result of a business event
 Recordkeeping items

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 28


Finding the Classes in a Problem (3 of 4)
2. Identify all nouns in the description, each of which is
a potential class
– Should include noun phrases and pronouns
– Some nouns may appear twice

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 29


Finding the Classes in a Problem (4 of 4)
3. Refine the list to include only classes that are
relevant to the problem
– Remove nouns that mean the same thing
– Remove nouns that represent items that the program
does not need to be concerned with
– Remove nouns that represent objects, not classes
– Remove nouns that represent simple values that can
be assigned to a variable

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 30


Identifying a Class’s Responsibilities
• A classes responsibilities are:
– The things the class is responsible for knowing
 Identifying these helps identify the class’s data attributes
– The actions the class is responsible for doing
 Identifying these helps identify the class’s methods

• To find out a class’s responsibilities look at the


problem domain
– Deduce required information and actions

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 31


Summary
• This chapter covered:
– Procedural vs. object-oriented programming
– Classes and instances
– Class definitions, including:
 The self parameter
 Data attributes and methods
 __init__ and __str__ functions
 Hiding attributes from code outside a class
– Storing classes in modules
– Designing classes

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 10 - 32


Starting out with Python
Fifth Edition, Global Edition

Chapter 11
Inheritance

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 1


Topics
• Introduction to Inheritance
• Polymorphism

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 2


Introduction to Inheritance (1 of 2)
• In the real world, many objects are a specialized
version of more general objects
– Example: grasshoppers and bees are specialized types
of insect
 In addition to the general insect characteristics, they
have unique characteristics:
– Grasshoppers can jump
– Bees can sting, make honey, and build hives

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 3


Introduction to Inheritance (2 of 2)

Figure 11-1 Bumblebees and grasshoppers are specialized versions of an insect

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 4


Inheritance and the “Is a” Relationship
(1 of 4)

• “Is a” relationship: exists when one object is a


specialized version of another object
– Specialized object has all the characteristics of the
general object plus unique characteristics
– Example: Rectangle is a shape
Daisy is a flower

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 5


Inheritance and the “Is a” Relationship
(2 of 4)

• Inheritance: used to create an “is a” relationship


between classes
• Superclass (base class): a general class
• Subclass (derived class): a specialized class
– An extended version of the superclass
 Inherits attributes and methods of the superclass
 New attributes and methods can be added

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 6


Inheritance and the “Is a” Relationship
(3 of 4)

• For example, need to create classes for cars, pickup


trucks, and SUVs
• All are automobiles
– Have a make, year model, mileage, and price
– This can be the attributes for the base class
• In addition:
– Car has a number of doors
– Pickup truck has a drive type
– SUV has a passenger capacity

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 7


Inheritance and the “Is a” Relationship
(4 of 4)

• In a class definition for a subclass:


– To indicate inheritance, the superclass name is placed
in parentheses after subclass name
 Example: class Car(Automobile):
– The initializer method of a subclass calls the initializer
method of the superclass and then initializes the
unique data attributes
– Add method definitions for unique methods

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 8


Inheritance in UML Diagrams (1 of 2)
• In UML diagram, show inheritance by drawing a line
with an open arrowhead from subclass to superclass

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 9


Inheritance in UML Diagrams (2 of 2)

Figure 11-2 UML diagram showing inheritance

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 10


Polymorphism (1 of 2)
• Polymorphism: an object’s ability to take different
forms
• Essential ingredients of polymorphic behavior:
– Ability to define a method in a superclass and override
it in a subclass
 Subclass defines method with the same name
– Ability to call the correct version of overridden method
depending on the type of object that called for it

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 11


Polymorphism (2 of 2)
• In previous inheritance examples showed how to
override the __init__ method
– Called superclass __init__ method and then added
onto that
• The same can be done for any other method
– The method can call the superclass equivalent and add
to it, or do something completely different

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 12


The isinstance Function
• Polymorphism provides great flexibility when
designing programs
• AttributeError exception: raised when a method
is receives an object which is not an instance of the
right class
• isinstance function: determines whether object is
an instance of a class
– Format: isinstance(object, class)

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 13


Summary
• This chapter covered:
– Inheritance, including:
 “Is a” relationships
 Subclasses and superclasses
 Defining subclasses and initializer methods
 Depicting inheritance in UML diagrams
– Polymorphism
– The isinstance function

Copyright © 2022 Pearson Education, Ltd. All Rights Reserved. 11 - 14

You might also like