(BQ) Part 2 book The practice of computing using python has contents: Functions—QuickStart, lists and tuples, more on functions, dictionaries and sets, more program development, introduction to classes, more on classes, program development with classes, files and exceptions II,... and other contents.
Trang 1Chapter 7 Lists and Tuples
Chapter 8 More on Functions
Chapter 9 Dictionaries and Sets
Chapter 10 More Program Development
Trang 2This page intentionally left blank
Trang 3• 6
C H A P T E R
Functions -QuickStart
Function, the exercise, or executing of some office or charge
T Blount, Glossographia, 1656, earliest definition offunction
in the Oxford English Dictionary
YOU HAVE SEEN MANY EXAMPLES OF USING PYTHON BUILT-IN FUNCTIONS AND
methods In Section 4.3.1, we took at look at how functions work and how we could use them
to manipulate string objects In this chapter, you’ll learn how to create your own functions.The concept of a function should be familiar from its use in mathematics Functions
in programming languages share many of the characteristics of mathematical functions butadd some unique features as well that make them more useful for programming
One of the main advantages for using functions is that they support divide-and-conquerproblem solving Remember divide-and-conquer from Section 3.4.5? This technique en-courages you to break a problem down into simpler subproblems, solve those subproblems,and then assemble the smaller solutions into the overall solutions Functions are a way todirectly encode the “smaller subproblem” solution You’ll see more about this as we workthrough this chapter
6.1 W H A T I S A F U N C T I O N ?
In mathematics, a function defines the relationship between values Consider the function
f (x )⇒√x If you provide a particular value of x , e.g., x = 4, the function will perform
a calculation (here the square root operation) and return the associated value, e.g., 2
Mathematicians term the variable x the argument to the function and say that the function
returns the value 2.
It is possible for a function to have multiple arguments—for example, a function that
cal-culates multiplication requires two arguments: f (x , y ) ⇒ x ∗ y However, a mathematical
257
Trang 4258 C H A P T E R 6 • F U N C T I O N S - Q U I C K S T A R T
function returns only one object Note that the returned object can be a compound object—
an object with multiple elements For example, when working with graph paper, each point
is represented by by its x and y coordinates, an ordered pair (x , y ) A function that returns an
ordered-pair object does indeed return a single value, but it is a value with multiple elements,
the x and y values An example of such a function would be the mirror function The mirror function swaps the x and y values of the ordered pair: f (x , y ) ⇒ (y , x) The notion that
the object a function returns can be a compound object is very useful, including in Python.Python functions share many of the characteristics of mathematical functions In par-ticular, a Python function:
rRepresents a single operation to be performed
rTakes zero or more arguments as input
rReturns one value (potentially a compound object) as output
A function is also important because it represents an encapsulation By encapsulation,
we mean that the details of an operation can be hidden, providing coarser operations that
we as programmers can use without having to understand the function’s internal details Afunction can represent the performance of an operation without making the reader plow
through the details of how the operation is actually performed.
Consider thesqrt function with respect to encapsulation There are many ways tocalculate a square root that vary in accuracy and speed Remember, we saw a particularapproach that we called the Babylonian square root approach in Section 3.5 Other imple-mentations exist However, each implementation, each method, represents the “square root”operation Each method takes in an argument and returns that object’s square root As long
as the result is correct, we need not be concerned with the details of how the operation isperformed That is encapsulation
6.1.1 Why Have Functions?
As you progress in learning to program, you’ll move from essential programming elements
to important programming elements Selection (if) and repetition (while) are essentialprogramming constructs It is difficult to write any program without using these two essential
features Functions, on the other hand, allow us to write better code in the sense that it is
more readable Also, because functions allow us to divide programs into smaller pieces, they
assist in divide-and-conquer problem solving In that way, functions make programs easier
to write Finally, once a function is written, it can be shared and used by other programmers
(including ourselves) Thus, functions provide a powerful construct that we can use to makeour programs easier to read, write, and maintain
From this point on, many of the programming elements we introduce will makesome tasks easier and will subsequently make writing and understanding (that is, reading)the program easier You could write programs without them, but those programs would bemore difficult to read, write, and maintain
Trang 56 2 • P Y T H O N F U N C T I O N S 259
In more detail, functions provide the following features, which help in programming:
r Divide-and-conquer problem solving: As we have already mentioned, functionsdivide programs into smaller pieces, an approach that corresponds nicely to a divide-and-conquer approach to problem solving (introduced in Section 3.4.5)
r Abstraction: Functions provide a higher-level interface to operation that the functionimplements By encapsulating details, functions provide a programmer with a high-levelview of the function’s operation that could be implemented in multiple ways—possibly
by someone else By analogy, consider how you drive a car It has a simple interface thathides considerable complexity Your car has many options—for example, fuel-injection,turbo, or many others Does the existence of these options change that basic interfaceyou have to the car—i.e., turn the wheel, hit the gas, press the brake? Do you understandhow fuel injection provides better performance for your car than a carburetor does? Doyou care? You don’t have to know the difference: you simply drive the car Abstractionmeans that the operation the function represents (drive the car) can be implemented
in many ways that do not affect the basic car interface The underlying operations canalso be changed (upgrade the engine) without changing the interface
r Reuse: Once a function has been created, it can be reused If you write a function thatlocates strings in a database, then anywhere that functionality is needed can use thatfunction The more such a function is needed, the “simpler” the code that uses it
r Sharing: Once your function is well tested, you can distribute it for use by other people.Those people can further test the function, refine its capabilities, and through improve-ment provide a service to everyone in the field Useful functions can be collected intomodules for sharing Sharing of modules is one of Python’s strengths, as programmersgenerously share modules in many diverse areas
r Security: You hear again and again of security breaches in code: phone companies,computer distributors, software companies, etc One way to battle security issues isthe use of functions Small pieces of code can be more easily vetted and security (andother issues) more easily addressed Once they have been approved, they can be used
to construct other secure components, which can also be reused, and so on Buildingsecurely from the bottom up is one approach to writing secure code
r Simplification and readability (duplication removal): Because a function provides anencapsulation, it can be used to simplify a program and make it more readable Anywherethat multiple lines of code might be needed to address a problem, a function can replacethose lines If the replacement can be done in multiple places, the result is simpler code
Trang 6260 C H A P T E R 6 • F U N C T I O N S - Q U I C K S T A R T
definition is the second way we have seen to create a name associated with an object in
Python, the first being an assignment statement
Consider an example function that converts Celsius temperatures to Fahrenheit
rFirst we need a conversion formula: C ∗ 1.8 + 32
rMathematics has a function invocation:
but the Python definition looks quite different:
def f(celsius float):
return celsius float* 1.8 + 32
As in mathematics, C is called an argument of the function Thecelsius float
variable is termed a parameter of the function Upon invoking the function, the argument
C’s value is passed to the parameter valuecelsius float for use in the calculation.2More detail on the passing of values between arguments and parameters can be found inSection 8.1.1
A function definition begins with the keyword def The Python definition workssimilarly to an assignment statement By executing adefstatement, a new name is created
in the namespace and a new object, a function object, is associated with that name As wehave observed elsewhere in Python, everything is an object, and functions are no different.Thedefis a compound statement, meaning that it provides a suite of other Pythonstatements and expressions that are part of the function The suite of statements are whatwill constitute the calculation done by the function object One of the special keywordsthat can be used in functions is the return statement The return indicates a valuethat is returned as output from the function invocation A function’s operation ends after a
returnstatement is executed A function may have more than onereturnstatement, butthe first one that is executed will end the function’s operation (We have used the phrase “to
invoke a function,” but an equivalent and frequently used phrase is “to call a function.”)
The general form of a function is shown in Figure 6.1
Let’s create a function to do our temperature conversion and use it in a session.Note the parts of the function: thedefandreturn keywords as well as the parameter(celsius float) Finally, notice the indentation for the suite of statements, part of the
2 Note that to adhere to our naming convention, the argument C should have been named better, such as celsius float, but we
Trang 76 2 • P Y T H O N F U N C T I O N S 261
def function_name (parameter1, parameter2) : statement1
statement2 return value_to_return
Keyword indicating function is being defined.
Return statement indicates the value returned when the func- tion finishes.
Function suite:
contains code to perform some action
Indented.
Suite of the function follows the colon.
FIGURE 6.1 Function parts.
function definition We will discuss the special comment with triple quotes (""") later In
essence, it is a brief description of the function and is called a docstring.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Trang 8262 C H A P T E R 6 • F U N C T I O N S - Q U I C K S T A R T
NameError: name 'new fn' is not defined
>>> new fn = "a string object"
>>> new fn
'a string object'
>>> new fn()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
It is the parentheses that mark the invocation, and the name adjacent to the parentheses
is the function invoked In the session, we converted 100◦C to 212◦F and 0◦C to 32◦F Ifthe function is not defined, or if the object associated with a name is not a function object,then an error occurs, as is shown in the session
a larger program
In short, the flow of control with functions is to flow from the invocation (call) inthe calling program, to the function itself, and then back to the calling program with
the function’s return value being made available to the calling program Control within a
function remains sequential: one statement after another along with local control statementssuch asifandwhile
For every program, there is usually one “main” part where execution begins After that,the flow of control is based on the order of both statements and functions In particularfor functions, operation of a function is determined by when it is invoked, not when it isdefined Functions can be defined anywhere in the program file, as long as they are defined
before they are invoked Functions must be defined before use because the function name
must be placed in the namespace before it can be called
Figure 6.2 shows an example of function control flow
Trang 96 3 • F L O W O F C O N T R O L W I T H F U N C T I O N S 263
Main program statement fahrenheit = celsius_to_fahrenheit(25) statement
statement
def celsius_to_fahrenheit(celsius): val = celsius * 1.8 + 32 return val
Function
Return
Call
FIGURE 6.2 Function flow of control.
6.3.1 Function Flow in Detail
Consider two programs: the caller, the program presently executing, and the function In this
example, the caller is the main program, the program where execution begins A caller cutes its statements until it encounters a function invocation,celsius to fahrenheit(25) in Figure 6.2 At that point, the caller temporarily suspends, and the functionbegins Thus, one program is suspended (the caller) waiting for a result from the nowexecuting function When the function finishes execution, the suspended caller receivesthe return value from the function and the main program (caller) resumes execution fromthat point
exe-Because the function is essentially a new program, the function gets its own namespacewhen it begins execution Any object that gets created and given a name (by assignment,
by adef, etc.) within the function is placed in the function’s separate namespace, not the
main program’s (caller’s) namespace If a new name is created in the function that is thesame as a name that existed in the caller’s namespace, the newly created association is used
in the function This protocol has some interesting consequences, which we will explore inSection 8.1.1
Parameter passing is done just before the calling program suspends The caller associatesits argument values to the corresponding function parameter in the function object InFigure 6.2, the argument value 25 is associated with the parametercelsius The parameter
is then defined in the function’s namespace and associated with the value of its correspondingargument After that, function operation begins
Trang 10264 C H A P T E R 6 • F U N C T I O N S - Q U I C K S T A R T
Argument values are typically passed to parameter names in the order they are listed.3The names of the corresponding argument and parameter need not match Only the ordermatters: the first argument value is passed to the first parameter, the second argument value
to the second parameter, and so on The number of arguments and parameters must match.4Again, after values are passed, the function then begins execution
During function execution, if a return statement is executed, the function endsand the return value is provided to the caller (“return” arrow in Figure 6.2) For example,fahrenheit = celsius to fahrenheit(25)assigns the returned value to the mainprogram variablefahrenheitas shown in Figure 6.2 After the function ends, the callercontinues
Code Listing 6.2 is a sample program with a function that takes in a Celsius temperature
7 # main part o f the program
8 print("Convert Celsius to Fahrenheit.")
9 celsius float = float(input("Enter a Celsius temp: "))
10 # c a l l the conversion function
11 fahrenheit float = celsius to fahrenheit(celsius float)
12 # print the returned value
13 print(celsius float," converts to ",fahrenheit float," Fahrenheit")
>>> ================================ RESTART ================================
>>>
Convert Celsius to Fahrenheit.
Enter a Celsius temp: 100
100.0 converts to 212.0 Fahrenheit
>>> ================================ RESTART ================================
>>>
Convert Celsius to Fahrenheit.
Enter a Celsius temp: 0
0.0 converts to 32.0 Fahrenheit
3 Python also has other ways to pass argument values to parameters See Chapter 8.
4
Trang 116 3 • F L O W O F C O N T R O L W I T H F U N C T I O N S 265
Lines 3–5 define the function Notice def beginning the compound statement, theparameter (celsius float), and thereturnwith its associated expression withinthe function suite To repeat, thedefstatement is executed by Python and creates thefunction Once created, it can be called (invoked) by another program Remember, afunction must be defined (thedefstatement must be executed) before a program cancall the function
Lines 7–13 are the “main” program.
Line 9 prompts the user for input.
Line 11 invokes (calls) the function The value in the argument celsius float
is passed to the parameter celsius float Then control passes to the tion When the function ends, it returns a value that the main program assigns tofahrenheit float
func-Line 13 The main program continues with func-Line 13 and prints the results.
Check Yourself: Simple Functions Check
1. Given the functionmake odd, what are the results of the four function invocations(print statements)?
2. Write a functionmake even(n)
What happens if you use a string as an argument?
Why is the behavior different then withmake odd(n)?
6.3.3 Another Function Example
You have used thelenfunction to find the length of a string Let’s write our own version
of that function that performs the same operation We will name our functionlengthtoavoid confusion with the Python built-inlen
Here is an algorithm to find the length of a string, S
r Initialize a counter:count = 0
r Iterate through each character of the string using aforloop:for char in a str:
r When each character is encountered in the for loop, add 1 to the counter:count += 1
Trang 12>>> question = "What is your quest?"
>>> length(question) # our function
19
>>> len(question) # the Python built −in function
19
With alengthfunction in hand, let’s modify it Suppose that instead of a count of
the number of characters in the string, we wanted a count of only the letters in the string.
That is, we will ignore characters other than lowercase alphabetic letters (such as numbers,spaces, punctuation, etc.) Our algorithm is similar:
rInitialize a counter.
rIterate through each character of the string using aforloop.
rFor each character in the string, if the character is a letter, add 1 to the counter.The change in the algorithm is small, but the implementation takes a little morethought How do we check “if the character is a letter”? One way to do that is to create
a variable associated with a string of all the lowercase letters We can then check if eachcharacter we encounter in the parametera strisin(rememberintests for membership)the lowercase letters However, Python has created for us a number of these strings that
we can test against As discussed in Section 4.6.2, we could use a variable from the stringmodule, the stringstring.ascii lowercase Finally, we must consider what to dowith uppercase letters We have a choice: we could ignore them (not include them in thecount), or we could include them by converting everya strcharacter to lowercase before
Trang 136 3 • F L O W O F C O N T R O L W I T H F U N C T I O N S 267
we test for membership We can handle that by making the character lowercase beforechecking to see whether it is in the string of letters We will call our modified functionletter count
Code Listing 6.4
1 import string
2
3 def letter count(a str):
4 """ Return the count o f l e t t e r s in a str """
6.3.4 Function Example: Word Puzzle
Let’s use strings and functions to solve a word puzzle
Find a word that contains the vowelsa, e, i, o, and u in that order in a string
To solve a word puzzle, we need a list of words
Reading a File of Words
Many word lists can be found on the Internet by searching for either “word lists” or
“dictionary,” usually with one word per line We can download a dictionary and save it in a
Trang 14268 C H A P T E R 6 • F U N C T I O N S - Q U I C K S T A R T
file; let’s name the file dictionary.txt We have worked with files in Section 5.7.1 and will do
so in more detail in Chapter 14, but let’s review how to read the contents of a file
To read through the file, one line at a time, we do the following:
rOpen the file for reading.
rRead through the file one line at a time.
A Python program that reads through the whole file dictionary.txt, and simply prints
each line of the file is Code Listing 6.5:
Code Listing 6.5
# Print a l l words in a d i c t i o n a r y f i l e that has one word per l i n e
# open f i l e named " d i c t i o n a r y t x t " f o r reading ( ' r ' )
data file = open("dictionary.txt", 'r')
# i t e r a t e through the f i l e one l i n e at a time
for line str in data file:
print(line str)
Interestingly, this program prints the lines of the file in double-space format Why isthat?5
Searching a File of Words
Now that you remember how to read through a file of words, let’s try to solve our puzzle.First, we need to handle a common feature of a file’s strings: there are often somecharacters that we don’t want to deal with In this case, the dictionary file contains a carriage-return character at the end of each line, and it may contain stray characters such as spaces ortabs We can eliminate such characters using thestripstring method, one of the methodslisted in Section 4.3.4 If no arguments are provided tostrip, then a new string is returned
with whitespace removed from either end of the calling string The calling string is not
modified If a string argument is provided tostrip, only those characters in the argumentstring are removed An example of its use isa str.strip('., '),which returns a newstring that strips commas, periods, and the space character from the beginning and end of
a str In particular,", this.".strip('., ')and" this,,.".strip('., ')both return the new string object'this' The blank character in the argument string ishard to see (after all, it is a blank), but it is there!
5
Trang 156 3 • F L O W O F C O N T R O L W I T H F U N C T I O N S 269
P R O G R A M M I N G T I P
The strip method works only on the beginning and end of a string For example,'this string'.strip()returns the string'this string' Because no argumentsare provided, the default behavior is to return a new string where whitespace (tabs, carriage
returns, space characters, etc.) are removed from the ends, but the space in the middle of the string is unaffected Note that all the whitespace characters are removed from the beginning
and the end
For every line we fetch from the file, we strip that line to remove whitespace at thebeginning and end of the line In addition, word puzzles are often easier if all charactersare known to be only lowercase (or only uppercase) The string methodloweris usefulfor that Let’s create a function that strips out whitespace characters and makes all of theremaining characters lowercase
Code Listing 6.6
def clean word(word):
""" Return word in l o w e r c a s e s t r i p p e d o f whitespace """
Code Listing 6.7
# Find a word with a s i n g l e example o f the vowels a , e , i , o , u in that order
data file = open("dictionary.txt", "r")
def clean word(word):
""" Return word in l o w e r c a s e s t r i p p e d o f whitespace """
return word.strip().lower()
# main program
for word in data file: # f o r each word in the f i l e
word = clean word(word) # clean the word
Trang 16Solving the Puzzle
To solve this puzzle, we want to determine the vowels and their order in a word Let’s write
a function that returns the vowels found in a word in the order in which they were found Afunction lets us consider each word in isolation For any word, we can check each character
to see whether it is a vowel and collect the vowels into a string in the order in which theywere found To begin, we create a variable that is associated with the empty string, with theintent that we will add discovered vowels to that string Our algorithm is:
rCreate an empty string; let’s call itvowels in word.
rFor each charactercharin the word
- ifcharis a vowel, add it to the stringvowels in word.How do we check whether a character is a vowel? We can create a string of vowelsvowels strand associate it with'aeiou'and check to see whether each character inthe dictionary entrywordisin(is a member of )vowels str
Here is our algorithm implemented as a function
Code Listing 6.8
def get vowels in word(word):
""" Return vowels in s t r i n g word −−include repeats """
vowel str = "aeiou"
vowels in word = ""
for char in word:
if char in vowel str:
vowels in word += char
return vowels in word
Let’s try the function out in a session to find the vowels in the word'create' Thevowels in'create'in order are'eae'
>>> word = "create"
>>> get vowels in word(word)
'eae'
Trang 17r Open the file.
r For each word in the file
- strip the word
- if the word is too small, skip it
- get the vowels in the word
- if the vowels returned is exactly'aeiou', print the original word
Using that algorithm as the main part of our program, let’s put it all together
5 def clean word(word):
6 """ Return word in l o w e r c a s e s t r i p p e d o f whitespace """
7 return word.strip().lower()
8
9 def get vowels in word(word):
10 """ Return vowels in s t r i n g word −−include repeats """
11 vowel str = "aeiou"
12 vowels in word = ""
13 for char in word:
14 if char in vowel str:
15 vowels in word += char
16 return vowels in word
17
18 # main program
19 print("Find words containing vowels 'aeiou' in that order:")
20 for word in data file: # f o r each word in the f i l e
21 word = clean word(word) # clean the word
22 if len(word) <= 6: # i f word i s too small , s k i p i t
24 vowel str = get vowels in word(word) # g e t vowels in word
25 if vowel str == 'aeiou': # check i f you have e x a c t l y a l l
vowels in order
print(word)
Trang 18Check Yourself: Function Practice with Strings
1. Give the output provided by the following program on the indicated input values.def func1 (str1, str2):
Trang 19There are a couple of points that are worth noting about the example.
r The use of functions made our problem-solving task easier The functions allowed us toconsider the problem in smaller pieces—the divide-and-conquer technique introduced
in Chapter 3
r The main program is very readable Even if we did not know the implementation ofthe functionsclean wordandget vowels in wordwe could guess what they(likely) did and understand what the program was trying to do
r Note the reuse of the identifier vowel strin both the main program and in thefunctionget vowels in word Because the function gets its own namespace, theseidentifiers are associated with different objects More on this in Section 8.1
6.3.5 Functions Calling Functions
There is no limitation to when a function can be called (except that it must be after its
def) It is often the case that a function will call another function This extension does notchange the process described previously, though it does make the flow of control slightlymore complicated for us to follow More on this in Chapter 8 In fact, a function can callitself—a complicated control flow to which we devote Chapter 16
6.3.6 When to Use a Function
There are no hard or fast rules about when to write something as a function or when to leavecode as part of a larger program However, here are some guidelines that may prove helpful
Only one purpose: A function should be the encapsulation of a single, identifiable
opera-tion A function should do one thing, and of course, do it well Functions that try to dotoo many things are candidates to be broken into multiple functions (i.e., refactored)
Readable: A function should be readable This is a reiteration of our venerable R ULE 2 Not too long: A function shouldn’t be too long What is “too long” depends on many
things, but the idea is that if a function does one thing, a person should be able to
Trang 20274 C H A P T E R 6 • F U N C T I O N S - Q U I C K S T A R T
read it easily and understand its purpose If the function is too long, difficult to followsomehow, it might need to be broken into multiple functions
Reusable: A function should be reusable in contexts other than the program it was written
for originally If possible, the function should be self-contained and not dependent onsome nuance of the calling program If it has dependencies then those dependenciesshould be made clear so that others can use it more easily
Complete: A function should be complete, in that it works in all potential situations If you
write a function to perform one thing, you should make sure that all the cases where it
might be used are taken into account It is often the case that the core of the function isvery straightforward, but handling all the cases it might encounter requires supportingcode
Able to be refactored: We first mentioned the term refactoring in Section 2.2.9 Again,
refactoring is the process of taking existing code and modifying it such that its structure
is somehow improved but the functionality of the code remains the same Functions canplay a prominent role in this process, as they allow you to take long, difficult-to-followcode and break it into smaller, more manageable pieces If you need to “fix” some code,consider refactoring it into functions
The idea that a function should “do one thing” is important enough that we will make it
if there is a good reason to make a function longer than that
6.3.7 What If There Is No Return Statement?
Sometimes we write functions without a return statement Functions that do not return a
value are often called procedures.
In that case, what, if anything, is returned? The answer is that a special Python valueNoneis returned by default if the programmer does not provide a return statement.Noneis a kind of odd Python value—a value to represent nothing Kind of cosmic!There are some good reasons to use a procedure One that often comes up is speciallyformatted output Formatting output to look “pretty” can be laborious and potentiallycomplicated A print procedure is therefore a good place to do such output The procedureisolates all the printing format but does not return a value Other instances might require achange of state to the program, something like turning a graphics mode on or off or changing
Trang 216 3 • F L O W O F C O N T R O L W I T H F U N C T I O N S 275
the network connection to a different mode Each of these elements is best isolated as aprocess, but as a function they do not need to return a value
To see this process in action, let’s write a trivial function that simply prints its parameter
We will then assign the result of the function to a variable When we print the value of thevariable, we see thatNonewas printed
>>> def formatted output(my str, my int):
print('The result of the processing for',my str, 'was', my int)
# no return statement
>>> formatted output('Bill',100)
The result of the processing for Bill was 100
>>> result = formatted output('Fred',75) # capture the i m p l i c i t return
The result of the processing for Fred was 75
>>> print(result)
>>>
6.3.8 What if There Are Multiple Return Statements?
If there are multiple return statements, the first return encountered during the operation ofthe function stops the function at that point and returns that value Consider the followingexample function, which returns “positive,” “negative,” or “zero,” depending on the value
Note that the function works correctly whether the argument passed in is anintor
a float For that reason neither suffix is used in the name Multiple return values canmake following the flow of control in the function more difficult for the reader to follow
If possible, it is best to have as few returns as possible so the reader can more clearly followthe function
Trang 22In this chapter, we introduced the concept of functions in a programming language andshowed how functions work in Python Of particular importance is that functions aid us inthe divide-and-conquer approach to problem solving After covering the list data structure
in the next chapter, we revisit functions to examine the complexities of passing mutableobjects to functions
Trang 23E X E R C I S E S 277
r Caller’s arguments map to the function’s parameters in order left to right.
r A function has its own namespace.
r Parameters are in the function’s namespace.
r A function must be defined before it is called.
r Defining a function puts its name in the caller’s namespace.
r Syntax, function definition:
def function name(parameter list):
# statement suite
return# something
Rules
r R ULE 1: Think before you program!
r R ULE 2: A program is a human-readable essay on problem solving that also happens
to execute on a computer
r R ULE 3: The best way to improve your programming and problem skills is to practice!
r R ULE 4: A foolish consistency is the hobgoblin of little minds.
r R ULE 5: Test your code, often and thoroughly!
r R ULE 6: If it was hard to write, it is probably hard to read Add a comment.
r R ULE 7: All input is evil, until proven otherwise.
r R ULE 8: A function should do one thing.
Exercises
1. Draw the parts of a function and label the parts Write a brief definition for each part
2. What are three guidelines used to determine whether creating a separate function is thesensible thing to do?
3. What does this function do? What does it return for num = 5?
Trang 24(b) Write a function that takes the choice of the user and makes calls to the otherfunctions that correspond to the operation to be performed (Give meaningful
names to the functions You don’t have to write the other function definitions.)
8. Write a function that takes in the final scores of two soccer teams as arguments andprints either who won the game or whether the game was tied Refer to the teams as
“Team1” and “Team2.” The function returns nothing
9. Write a function that takes as input an English sentence (a string) and prints the totalnumber of vowels and the total number of consonants in the sentence The functionreturns nothing Note that the sentence could have special characters like dots, dashes,and so on
Trang 25E X E R C I S E S 279
10. The Fibonacci sequence is: 1, 1, 2, 3, 5, 8, 13 You can see that the first and secondnumbers are both 1 Thereafter, each number is the sum of the previous two numbers
(a) Write a function to print the first N numbers of the Fibonacci sequence.
(b) Write a function to print the Nth number of the sequence
11. Suppose you are purchasing something online on the Internet At the website, you get
a 10% discount if you are a member Additionally, you are also getting a discount of5% on the item because its Father’s Day
Write a function that takes as input the cost of the item that you are purchasing and
a Boolean variable indicating whether you are a member (or not), applies the discountsappropriately, and returns the final discounted value of the item
Note: The cost of the item need not be an integer
12. A leap year in the Gregorian calendar system is a year that’s divisible by 4 but not by
100, unless it is also divisible by 400 For example, 1896, 1904, and 2000 were leapyears but 1900 was not Write a function that takes in a year as input and prints whetherit’s a leap year (or not)
13. Error checking with meaningful error messages is an important part of programming.Consider the following scenario: A customer has to pay his monthly credit card bill.The credit limit on the card is $1000 The minimum payment due is always $20.Let the payment on the credit card be$P Write a function calledmake payment(P)that takes as an argument the total payment on the credit card ($P) and prints “Success”
or “Retry.” Try to think of all the errors that should be taken care of and implementthose in the function One example would be that if the payment is less than$20, theprogram should remind the user that it’s less than the minimum payment due
14. You buy an international calling card to India The calling card company has somespecial offers
(a) If you charge your card with$5 or$10, you don’t get anything extra
(b) For a$25 charge, you get$3 of extra phone time
(c) For a$50 charge, you get$8 of extra phone time
(d) For a$100 charge, you get$20 of extra phone time
Write a function that asks the user for the amount he/she wants on the card and returnsthe total charge that the user gets Note: Values other than those mentioned above arenot allowed
15. Chat:
(a) In certain chat programs or messaging applications, there is a limit on the number
of characters that you can send in a message Write a function that takes as inputthe message (a string) and checks whether the number of characters is less than
160 (or not) If the length of the message is less than 160, the message should bereturned If the length of the message is greater than 160, a string consisting of onlythe first 160 characters should be returned
Trang 2617. (Refactoring) In Chapters 1 and 2, there were exercises to calculate football quarterbackpass ratings and then to output the quality of the quarterback.
(a) Write the pass rating as a function Have the main program prompt for the fiveinputs and then use those inputs as arguments to the function
(b) Write the quality rating as a function and add it to the existing program
18. In an exercise in Chapter 2, we presented an odometer puzzle from the Car Talk radio
program that involved numerical palindromes Refactor your solution by writing apalindome function and using that in your solution
19. Write a function that takes as input a string that stores date and time (24-hour clock)
in the following format:
“MM/DD/YYYY HR:MIN:SEC” and prints the following:
rDD/MM/YYYY
rHR:MIN:SEC
rMM/YYYY
rWhether the time is a.m or p.m.
Validation of the input in the function is necessary For example, if the user gives
an input of “122/04/1990 13:12:12”, the given string is invalid, as there can be only
12 months in a year Think of all possible erroneous inputs and write code to handlethem The function doesn’t return anything
20. Write a function that takes as input a string that stores date and time in the format
“MM/DD/YYYY HR:MIN:SEC” and prints the number of seconds elapsed since
“01/01/YYYY 00:00:00”
21. Write a function that prints all numbers in the range A to B (inclusive) that haveall digits belonging to the set{1,3,4,8,9} Check whether A is less than or equal toB; otherwise, swap them before proceeding The function takes two integer arguments:
A and B
22. Given a string of length three representing a set (i.e., surrounded by curly braces) such as
"{ABC}", write a function that takes the string as an argument and returns a string of itspermutations in comma-separated form, such as"{ABC, ACB, BAC, BCA, CAB, CBA}" Hint: use multipleforloops
23. Implement a textual progress bar in Python In any progress bar, the space occupied
by it is finite Let’s say the textual progress bar could show only 10 Xs So you have to
Trang 27Programming Projects
1 U.S Flag in Turtle Graphics:
Draw the United States flag using at least four functions The regular polygons in the
US flag are natural candidates for functions
(a) Draw the flag shown earlier in the chapter with 13 stars arranged in rows Addcolor for maximum effect
(b) Draw the flag with the 13 stars arranged in a circle (Hint: Is it really a circle, or is
it some other regular figure?)
(c) Rewrite your program so it takes as input one positive real number that specifies ascale factor That is, 0.5 will cause a half-size flag to be drawn and 2.8 will draw aflag that is 2.8 times larger
2 DNA Sequencing:
The term DNA sequencing refers to methods for determining the order of the nucleotide
bases, adenine, thymine, cytosine, and guanine in a molecule of DNA The standardrepresentation of the bases is to use their first letters, ATCG, so that DNA is represented
as a string using only those four characters However, DNA strings are millions of bases(characters) long
Substring matching is the process of determining whether a shorter string (the
substring) is contained within a longer string Substring matching plays importantroles in the reconstruction of an unknown DNA string from pieces and in searchingfor interesting substrings within a known DNA string
Python provides a find(substring, start, end) string method that
re-turns the lowest index (integer) where the substring is found in the index range
start≤index < end Thestartandendarguments are optional, but for thisexercise we will make them required (you will learn later how to handle optionalarguments) If the substring is not found, -1 is returned
(a) Without using thefindstring method, write a function that behaves exactly likethefind string method As your function is not a string method, the string to
Trang 28282 C H A P T E R 6 • F U N C T I O N S - Q U I C K S T A R T
search must be an argument—let’s make it the first one The resulting format ofyour function will be:
find(some string, substring, start, end)
(b) Biology researchers frequently want to find all the locations where a substring
is found, not simply the first one Write a function named multi find(some string, substring, start, end) that, instead of returning oneinteger index, returns a string that contains zero or more indices separated bycommas In this case, the string will contain digits representing the integer indices
If the substring is not found, an empty string is returned You may use thefindmethod that you wrote earlier
(c) A nice feature of ourmulti findfunction is that if the substring is not found, anempty string is returned In particular, if the substring is not found, the returnedempty string resolves to be Falsein a Boolean expression The returned valuewill be True otherwise That feature allows one to usemulti find in an if
statement, such as:if multi find(S,substring,0,20) The Pythonfindstring method does not share that characteristic (why?) Write a program thatexercises both yourfindand yourmulti findfunctions including their use inBoolean expressions Create some strings using only the base letters, ATCG, andsearch for substrings within them
3 Heap of Beans:
We are going to play a game called the heap of beans You start with a heap of beans
(we will start with 16 beans) and two players Each player can remove 1, 2, or 3 beansfrom the pile of 16 Each player is required to take some number of beans from the pileduring each turn The players take turns removing beans, and the player who takes thelast bean from the pile is the loser You can try this game with a partner using 16 pieces
of paper as beans
Each player is to be represented by a function, so we will have two functions.Each function takes a single argument, representing the present number of beans, andreturns the number of beans remaining after the player function takes its turn Duringthe operation of the player function, the function reports (prints) how many beanswere removed Note that the function decides how many beans to remove It takes noinput from the user
You also need a main program The main program initializes the heap of beans to
16 and then alternately calls the first player function and the second player functionuntil one of them gets the last bean The main then reports who the loser is and exits.(a) Write a simple player function such as one that always takes exactly one bean Itisn’t very interesting, but it lets you test your program
(b) Now for the fun part Write a “smart player” function and test it against otherstudents’ functions in your class A class tournament would be best—who has thebest strategy?
Trang 29• 7
C H A P T E R
Lists and Tuples
List, a Scrowl of the Names of several Persons of the same Quality with whom
we have Business
E Phillips, New World of Words, 1696
7.1 W H A T I S A L I S T ?
PYTHON’S BUILT-IN LIST TYPE IS ALSO A COLLECTION TYPE IN FACT, LIKE STRINGS,
lists are a sequence type and are an iterable type They therefore share some of the teristics of strings However, a list differs from a string in two fundamental ways:
charac-r A list can contain elements other than characters In fact, a list can contain a sequence
of elements of any type, even different typed elements mixed together in the same list.
r A list is a mutable type This means that, unlike a string object, a list object can bechanged after it is initially created
If we keep these differences in mind, we can use our knowledge of the string type towork with lists
Making Python Lists
Lists can be created with thelistconstructor or with square brackets ([ ]) This capabilitycan be a little confusing, as the same square brackets are also used as the index operator.One way to tell the difference is the presence of the comma character: each element of a list
is separated by a comma Thus, if you see square brackets with multiple elements separated
by commas, you know it is a list Otherwise, you will have to use the context to determinewhat the brackets mean
283
Trang 30284 C H A P T E R 7 • L I S T S A N D T U P L E S
Here are a few examples of making a list in a Python session:
>>> a list = [1,2,'a',3.14159]
>>> week days list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
>>> list of lists = [ [1,2,3], ['a','b','c']]
>>> list from collection = list('Hello')
>>> a list
[1, 2, 'a', 3.1415899999999999]
>>> week days list
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
Here are a few things to notice about these lists
ra listis a sequence of four elements (two integers, a character, and a floating-pointnumber) Any Python type can be a list element, and different types can be in the same
list Again, this differs from a string, which requires its elements to all be characters.
rAs previously noted, each element of the list is separated from the next by a comma.The comma indicates elements of a collection, and the square brackets indicate thatcollection is a list
rThelist of listsis a list of only two elements The first element is a list, as is thesecond Again, a list can be a sequence of any typed element—even another list!
rThelist from collectionis a list built using the constructorlist The ing list is['H', 'e', 'l', 'l', 'o'], containing five elements, each a single-character string This constructor takes a single argument and that argument must be
result-an iterable Thelistconstructor takes each element of the argument iterable and addsthat element to the new list Non-iterable types (integers, floats, Booleans, etc.) cannot
be used as an argument to thelistconstructor since they do not contain multipleelements (are not iterable)
rThe special list with no elements, designated as[], is called the empty list Like other
“empty” elements, it is equivalent to aFalsevalue in Python
Note the naming convention for lists As with other collections, we append the collectiontype to the end of the name, “list” for lists This protocol is similar to the naming convention
we have used for other types As per R ULE 4, we will violate this convention when a more
meaningful name is appropriate, such as thelist of lists
Trang 31>>> spreadsheet list = [ ['Name','Age','GPA'], ['Bill', 25, 3.55], ['Rich', 26 , 4 00]]
>>> row = spreadsheet list[1]
This concept generalizes to any level of nesting of lists For example, to represent the x y z
3-D plane, how would we approach it? This would be a list of lists of lists The outermostlist would represent a 2-D plane, the list within that list would represent the value of all the
values in a particular row (say x ), and then a particular value would be the index into that row (say y ).
7.2 W H A T Y O U A L R E A D Y K N O W H O W T O D O
W I T H L I S T S
Because lists are sequences and iterable, many things that you learned to do with strings alsowork for lists Let’s take a look and refresh your memory
Trang 32286 C H A P T E R 7 • L I S T S A N D T U P L E S
7.2.1 Iteration
As with a string, you can iterate through each element of a list using aforloop Because
a list is also a sequence, the elements are iterated through in the order set by the list Thefollowing session reminds you of how it works
>>> for element in ['abc', 12, 3.14159, True]:
print ("{:<7} which is type {}".format(element, type(element)))
abc which is type <class 'str'>
12 which is type <class 'int'>
3.14159 which is type <class 'float'>
1 which is type <class 'bool'>
>>>
This session emphasizes that a list is iterable and that the elements can be of any type
We also print out the results in a slightly more elegant way using string formatting
7.2.2 Indexing and Slicing
Indexing and slicing work exactly the same with lists and strings To remind yourself, look
rAccessing an element at an index that does not exist in the list is an error.
rThe slice operation is the same as with strings Within square brackets, you may haveone or two colons (:) The number before the first colon is the start index, the number
myList = [1, 'a', 3.14159, True]
myList
2 1
1
myList[1] → 'a' myList[:3] → [1, 'a', 3.14159]
Index forward Index backward
FIGURE 7.1 The structure of a list.
Trang 337 2 • W H A T Y O U A L R E A D Y K N O W H O W T O D O W I T H L I S T S 287
after the first colon is the end index, and the number after the second colon is the step.The defaults for all three are (in order): the beginning of the list, the end of the list,and a step of 1
r A slice uses a half-open range, meaning that the end index is not included in the slice.The following session shows these operations:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
7.2.3 Operators
You can use both the addition (+) and multiplication (*) operators with lists with resultssimilar to those of strings The addition operator takes two lists as operands and concatenatesthem together, making a new list whose contents are the first list joined at its end to thebeginning of the second list The multiplication operator takes a list and an integer asoperands The integer indicates how many times the list is replicated
Trang 34Comparison works as it did with strings, so you can use the >,<,==,<=,>=, and != signs
as operators between two list operands As with strings, comparison begins by ing the first element of each list If the first elements are equal, the comparison processmoves to the second element of each list The process continues in this way, comparingcorresponding elements, until the process finds that two elements are different At thatpoint, the comparison between the two different elements determines the result of theoperation If one list is equal to but shorter than the other list, the longer list is consideredgreater
compar-Finally, theinoperator for membership testing works as it did in strings The expression'a' in ['a','b','c']is a query, testing whether the first operand exists in the secondoperand In this case it does, returningTrue
The following session demonstrates these operations on lists:
>>> my list = [1,2,3]
>>> your list = ['a','b','c']
>>> concat list = my list + your list # concat l i s t s , operand unchanged
Trang 357 2 • W H A T Y O U A L R E A D Y K N O W H O W T O D O W I T H L I S T S 289
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
compar-Finally, comparisons underly other operations that depend on order, such as the sorting,maximizing, and minimizing operations discussed later in this chapter
7.2.4 Functions
There are a number of functions that work with any collection In particular, you haveseen thelenfunction With strings, thelenfunction returns the number of characters
in a string With lists, thelenfunction returns the number of comma-separated elements
in the list Again, remember that a list can have as an element another list and that liststill counts as one element Thus, the result oflen([1,[1,2,3],3])is 3 The secondelement, the element at index 1, is another list,[1,2,3] Here are some functions thatwork on collections, including lists:
len(C)Return the length of collection C, i.e., the number of elements
min(C) Return the minimum element in collection C If the argument is a list of lists,only the first element in each list is considered for the purposes of comparison
max(C) Return the maximum element in collection C If the argument is a list of lists,only the first element in each list is considered for the purposes of comparison
sum(L)Return the sum of elements in list L The particular function requires that the list
>>> str list = ['a', 'b', 'c', 'd', 'e']
>>> nested list = [int list, float list, str list]
>>> len(int list)
5
Trang 36>>> sum(str list) # elements must be numbers
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
sum(str list)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> min(nested list) # d i f f e r e n t t y p e s : 1 and ' a '
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
min(nested list) TypeError: unorderable types: str() < int()
>>> for element in my list: # i t e r a t e through l i s t elements
print(element ,end=' ') # p r i n t s on one l i n e
1 3 4 8
>>>
In this example, the variableelementis assigned the values 1, 3, 4, and 8, one at a time,and then the statement(s) in the suite are executed using that value forelement In thistrivial example, the print statement will execute with each value ofelementand print it
7.3 L I S T S A R E D I F F E R E N T T H A N S T R I N G S
We’ve seen what’s the same about lists and strings, so let’s look a bit more at what’s different
7.3.1 Lists Are Mutable
When we covered strings, we emphasized that they are immutable In particular, we notedthat you could not have a string index operator on the left-hand side of the assignment
Trang 377 3 • L I S T S A R E D I F F E R E N T T H A N S T R I N G S 291
statement In other words, you could not change a character of a string at some index within
an existing string to a different character Once created, the string cannot be changed
Lists, on the other hand, are mutable; the element at some index in a list can be changed This is called index assignment You can even change an entire slice of the list to be different! This is called slice assignment These two operations show both the power and one of the
dangers of mutable objects They are very flexible and very useful However, you must takecare in using them because you can accidentally change a list in ways you did not intend.Let’s see how mutability works in a session:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
Let’s note a few things about this session:
r A list in combination with the index operator can occur on the left side of the assignmentstatement This means that, after the assignment occurs, the value at that index ischanged to be the value of the right-hand side of the assignment statement This isindex assignment
r As a result of every operation in that session, the list is changed This means that everytime we perform one of these operations, the changed list is carried forward to the nextline in the session In other words, the list elements associated withmy listat theend of the session are the cumulative result of all the operations that came before, inthe order they were performed
r Because the assignment operator does not return a value, we have to type the name ofthe variable associated with the list to see what was changed as a result This is not new,
Trang 38being assigned must be a collection Each individual element of an assigned collection
is added to the list at the slice indicies You cannot slice assign an individual value to
a list, though the session shows that assigning a list with a single value is acceptable.Only assigning a collection makes some sense if you consider it for a moment A slice
is in fact a collection (a subsequence of the original), so to replace it implies that weneed another collection The collection replacing the slice can be bigger, smaller, orthe same size
7.3.2 List Methods
As we mentioned previously, a method is a function that works with a particular type ofPython object The string type has a large number of methods that can be applied to strings,
but those methods can be applied only to strings Lists have their own associated methods
that work only with lists The number of list methods is quite a bit smaller—only nine.They come in two different categories:
rThose that change the list
rThose that do not change the list
It is important that we keep those two categories straight, so we know whether our list
is changed as a result of using the method
Non-modifying methods
These methods do not change the list, but they return a value as a result of their processing.
index(x) Return the index of the first element in the list whose value is equal to x.
Python throws an error if there is no such value in the list
count(x)Return the number of times x appears in the list Returns 0 if x does not appear
in the list
Methods that Modify the List
There are two things to note about these methods First, the list that calls the method will
be modified as a result of the operation of the method Second, none of the methods exceptthepopmethod returns a value This fact may seem odd, but taking a closer look mayhelp In our previous experience, every string method returned a value: a new string object
Remember, though, that strings are immutable They had to return a value, typically a
string, so that the change could be captured These list methods do not need to return a listobject for the change, as the list itself is changed (it is mutable)
Trang 397 3 • L I S T S A R E D I F F E R E N T T H A N S T R I N G S 293
append(x)Append an element to the end of the list The length of the list is increased
by one The element is appended exactly, so a collection is added as a single element
pop() Remove the element at the end of the list and return that element The list isshortened by one element If an index is specified,a.pop(an index)removes theelement at that position and returns that item
extend(C)Requires a collection C as an argument The list is extended by adding each
individual element of the argument collection C to the end of the list.
insert(i, x)Insert an element at a given position The first argument is the index
before which to insert in the list Thus,my list.insert(1, 'a')inserts the'a'into position 1 of the list, sliding all the rest of the list elements down one (the element
at index 1 moves to index 2, the element at index 2 moves to index 3, and so on)
remove(x)Remove the first element from the list whose value is x An error results if
there is no such item The length of the list is decreased by one if successful
sort()Sort the elements of the list, in place If sorting a list of lists, only the first element
in each list is considered in the comparison operations Only the order of the listelements is modified (unless already sorted).1
reverse()Reverse the elements of the list, in place Only the order of the list elements
is modified
Let’s open a Python shell and demonstrate each method Remember the dot format for
methods, in which you provide a list object (an object of typelist), followed by a dot (.),followed by the method name:
Trang 40rIf you want to add the contents of another collection to the end, use extend Theextend method adds each of the individual elements of the argument collection tothe list, one at a time The addition begins a the end of the list The argument must be
a collection
rTheremovemethod searches for and removes a particular element, but it only removesthe first occurrence of that element If that element is not in the list, Python throws anerror Because of this behavior, its use is usually preceded by a check for that element’sexistence using theinoperator Theindexmethod, which returns the index of thefirst occurrence of an element, throws a similar error if the index is not found It is alsooften used in conjunction with anincheck
rThepopmethod gets its name from its association with a classic data structure called a
stack We will talk more about stacks in Chapter 16 Python will throw an error if you
try topopan empty list
rThesortmethod must be used with some care It works best with homogeneous lists—those containing all elements of the same type—due to difficulties in the comparison
of different types that we have discussed
P R O G R A M M I N G T I P
Ordering: when dealing with functions, methods, or operations that depend on ordering
(such assort, sorted, reverse, min, max, <, >, ==) use only homogeneouselements, e.g., all numbers or all strings Mixed types do not have a natural ordering andwill generate an error in Python