Introduction to Programming in Python: An Interdisciplinary Approach covers functions in Python, including using and defining functions, implementing mathematical functions, using functions to organize code, and passing arguments and returning values."> Defining Functions in Python | Using and defining functions | InformIT - 188bet足球靠谱

Home>Articles>Open Source>Python

Defining Functions in Python

This chapter fromIntroduction to Programming in Python: An Interdisciplinary Approach封面s functions in Python, including using and defining functions, implementing mathematical functions, using functions to organize code, and passing arguments and returning values.
This chapter is from the book

YOU HAVE BEEN COMPOSING CODE THATcalls Python functions since the beginning of this book, from writing strings with的头.writeln()to using type conversion functions such asstr()andint()to computing mathematical functions such asmath.sqrt()to using all of the functions in的头,stddraw, andstdaudio. In this section, you will learn how to define and call your own functions.

In mathematics, a function maps an input value of one type (the domain) to an output value of another type (the range). For example, the square functionf(x) =x2maps 2 to 4, 3 to 9, 4 to 16, and so forth. At first, we work with Python functions that implement mathematical functions, because they are so familiar. Many standard mathematical functions are implemented in Python’smathmodule, but scientists and engineers work with a broad variety of mathematical functions, which cannot all be included in the module. At the beginning of this section, you will learn how to implement and use such functions on your own.

Later, you will learn that we can do more with Python functions than implement mathematical functions: Python functions can have strings and other types as their domain or range, and they can have side effects such as writing output. We also consider in this section how to use Python functions to organize programs and thereby simplify complicated programming tasks.

From this point forward, we use the generic termfunctionto mean eitherPython functionormathematical functiondepending on the context. We use the more specific terminology only when the context requires that we do so.

Functions support a key concept that will pervade your approach to programming from this point forward:当你可以清楚地在一个单独的任务omputation, you should do so.We will be overemphasizing this point throughout this section and reinforcing it throughout the rest of the chapter (and the rest of the book). When you write an essay, you break it up into paragraphs; when you compose a program, you break it up into functions. Separating a larger task into smaller ones is much more important when programming than when writing an essay, because it greatly facilitates debugging, maintenance, and reuse, which are all critical in developing good software.

Using and defining functions

As you know from the functions you have been using, the effect of calling a Python function is easy to understand. For example, when you placemath.sqrt(a-b)in a program, the effect is as if you had replaced that code with thereturn valuethat is produced by Python’smath.sqrt()function when passed the expressiona-bas anargument. This usage is so intuitive that we have hardly needed to comment on it. If you think about what the system has to do to create this effect, however, you will see that it involves changing a program’scontrol flow.的implications of being able to change the control flow in this way are as profound as doing so for conditionals and loops.

You can define functions in any Python program, using thedefstatement that specifies the function signature, followed by a sequence of statements that constitute the function. We will consider the details shortly, but begin with a simple example that illustrates how functions affect control flow. Our first example, PROGRAM2.1.1 (harmonicf.py), includes a function namedharmonic()that takes an argumentnand computes thenth harmonic number (see PROGRAM1.3.5). It also illustrates the typical structure of a Python program, having three components:

  • A sequence ofimportstatements
  • A sequence offunction definitions
  • Arbitraryglobal code, or the body of the program

PROGRAM2.1.1 has twoimportstatements, one function definition, and four lines of arbitrary global code. Python executes the global code when we invoke the program by typingpython harmonicf.pyon the command line; that global code calls theharmonic()function defined earlier.

的implementation inharmonicf.pyis preferable to our original implementation for computing harmonic numbers (PROGRAM1.3.5) because it clearly separates the two primary tasks performed by the program: calculating harmonic numbers and interacting with the user. (For purposes of illustration, we have made the user-interaction part of the program a bit more complicated than in PROGRAM1.3.5.)当你可以清楚地在一个单独的任务omputation, you should do so. Next, we carefully examine precisely howharmonicf.pyachieves this goal.

Control flow

的diagram on the next page illustrates the flow of control for the commandpython harmonicf.py 1 2 3. First, Python processes theimportstatements, thus making all of the features defined in thesysand的头modules available to the program. Next, Python processes the definition of theharmonic()function at lines 4 through 8, butdoes not execute the function—Python executes a function only when it is called. Then, Python executes the first statement in the global code after the function definition, theforstatement, which proceeds normally until Python begins to execute the statementvalue = harmonic(arg), starting by evaluating the expressionharmonic(arg)whenargis1. To do so it transfers control to theharmonic()function—the flow of control passes to the code in the function definition. Python initializes the “parameter” variablento1and the “local” variabletotalto0.0and then executes theforloop withinharmonic(), which terminates after one iteration withtotalequal to1.0. Then, Python executes thereturnstatement at the end of the definition ofharmonic(), causing the flow of control to jump back to the calling statementvalue = harmonic(arg),继续从那里离开,但是现在the expressionharmonic(arg)replaced by1.0. Thus, Python assigns1.0tovalueand writes it to standard output. Then, Python iterates the loop once more, and calls theharmonic()function a second time withninitialized to2, which results in1.5being written. The process is then repeated a third time witharg(and thenn) equal to4, which results in2.083333333333333being written. Finally, theforloop terminates and the whole process is complete. As the diagram indicates, the simple code masks a rather intricate flow of control.

Program 2.1.1 Harmonic numbers (revisited)(harmonicf.py)

Informal function call/return trace

One simple approach to following the control flow through function calls is to imagine that each function writes its name and argument(s) when it is called and its return value just before returning, with indentation added on calls and subtracted on returns. The result enhances the process of tracing a program by writing the values of its variables, which we have been using since SECTION1.2. An informal trace for our example is shown at right. The added indentation exposes the flow of the control, and helps us check that each function has the effect that we expect. Generally, adding calls on的头.writef()to traceanyprogram’s control flow in this way is a fine approach to begin to understand what it is doing. If the return values match our expectations, we need not trace the function code in detail, saving us a substantial amount of work.

FOR THE REST OF THIS CHAPTER, your programming will be centered on creating and using functions, so it is worthwhile to consider in more detail their basic properties and, in particular, the terminology surrounding functions. Following that, we will study several examples of function implementations and applications.

p0214_01.jpg

Basic terminology

As we have been doing throughout, it is useful to draw a distinction between abstract concepts and Python mechanisms to implement them (the Pythonifstatement implements the conditional, thewhilestatement implements the loop, and so forth). There are several concepts rolled up in the idea of a mathematical function and there are Python constructs corresponding to each, as summarized in the table at the top of the following page. While you can rest assured that these formalisms have served mathematicians well for centuries (and have served programmers well for decades), we will refrain from considering in detail all of the implications of this correspondence and focus on those that will help you learn to program.

When we use a symbolic name in a formula that defines a mathematical function (such asf(x) = 1 +x+x2), the symbolxis a placeholder for some input value that will be substituted into the formula to determine the output value. In Python, we use aparameter variableas a symbolic placeholder and we refer to a particular input value where the function is to be evaluated as anargument.

concept

Python construct

description

function

function

mapping

input value

argument

input to function

output value

return value

output of function

formula

function body

function definition

independent variable

parameter variable

symbolic placeholder for input value

Function definition

的first line of a function definition, known as itssignature, gives a name to the function and to each parameter variable. The signature consists of the keyworddef; thefunction name; a sequence of zero or more parameter variable names separated by commas and enclosed in parentheses; and a colon. The indented statements following the signature define thefunction body. The function body can consist of the kinds of statements that we discussed in CHAPTER1. It also can contain areturn statement, which transfers control back to the point where the function was called and returns the result of the computation orreturn value. The body may also definelocal variables, which are variables that are available only inside the function in which they are defined.

p0215_01.jpg

Function calls

As we have seen throughout, a Python function call is nothing more than the function name followed by its arguments, separated by commas and enclosed in parentheses, in precisely the same form as is customary for mathematical functions. As noted in SECTION1.2, each argument can be an expression, which is evaluated and the resulting value passed as input to the function. When the function finishes, the return value takes the place of the function call as if it were the value of a variable (perhaps within an expression).

Multiple arguments

像一个数学函数,一个Python函数n have more than one parameter variable, so it can be called with more than one argument. The function signature lists the name of each parameter variable, separated by commas. For example, the following function computes the length of the hypotenuse of a right triangle with sides of lengthaandb:

defhypot(a, b) return math.sqrt(a*a + b*b)

Multiple functions

You can define as many functions as you want in a.pyfile. The functions are independent, except that they may refer to each other through calls. They can appear in any order in the file:

defsquare(x): return x*x def hypot(a, b): return math.sqrt(square(a) + square(b))

However, the definition of a function must appear before any global code that calls it. That is the reason that a typical Python program contains (1)importstatements, (2) function definitions, and (3) arbitrary global code, in that order.

Multiple return statements

You can putreturnstatements in a function wherever you need them: control goes back to the calling program as soon as the firstreturnstatement is reached. Thisprimality-testingfunction is an example of a function that is natural to define using multiplereturnstatements:

defisPrime(n): if n < 2: return False i = 2 while i*i <= n: if n % i == 0: return False i += 1 return True

Single return value

A Python function provides only one return value to the caller (or, more precisely, it returns a reference to one object). This policy is not as restrictive as it might seem, because Python data types can contain more information than a single number, boolean, or string. For example, you will see later in this section that you can use arrays as return values.

Scope

scopeof a variable is the set of statements that can refer to that variable directly. The scope of a function’s local and parameter variables is limited to that function; the scope of a variable defined in global code—known as aglobal variable—is limited to the.pyfile containing that variable. Therefore, global code cannot refer to either a function’s local or parameter variables. Nor can one function refer to either the local or parameter variables that are defined in another function. When a function defines a local (or parameter) variable with the same name as a global variable (such asiin PROGRAM2.1.1), the variable name in the function refers to the local (or parameter) variable, not the global variable.

A guiding principle when designing software is to define each variable so that its scope is as small as possible. One of the important reasons that we use functions is so that changes made to one part of a program will not affect an unrelated part of the program. So, while code in a functioncanrefer to global variables, itshould notdo so: all communication from a caller to a function should take place via the function’s parameter variables, and all communication from a function to its caller should take place via the function’s return value. In SECTION2.2, we consider a technique for removing most global code, thereby limiting scope and the potential for unexpected interactions.

Default arguments

A Python function may designate an argument to beoptionalby specifying adefault valuefor that argument. If you omit an optional argument in a function call, then Python substitutes the default value for that argument. We have already encountered a few examples of this feature. For example,math.log(x, b) returns the base-blogarithm ofx. If you omit the second argument, thenbdefaults tomath.e—that is,math.log(x)returns the natural logarithm ofx. It might appear that themathmodule has two different logarithm functions, but it actually has just one, with an optional argument and a default value.

You can specify an optional argument with a default value in a user-defined function by putting an equals sign followed by the default value after the parameter variable in the function signature. You can specify more than one optional argument in a function signature, but all of the optional arguments must follow all of the mandatory arguments.

For example, consider the problem of computing thenthgeneralized harmonic number of order r:Hn, r= 1 + 1/2r+ 1/3r+ ... + 1/nr. For example,H1, 2= 1,H2, 2= 5/4, andH2, 2= 49/36. The generalized harmonic numbers are closely related to the Riemann zeta function from number theory. Note that thenth generalized harmonic number of orderr= 1 is equal to thenth harmonic number. Therefore it is appropriate to use1as the default value forrif the caller omits the second argument. We specify by writingr=1in the signature:

defharmonic(n, r=1): total = 0.0 for i in range(1, n+1): total += 1.0 / (i ** r) return total

With this definition,harmonic(2, 2)returns1.25, while bothharmonic(2, 1)andharmonic(2)return1.5. To the client, it appears that we have two different functions, one with a single argument and one with two arguments, but we achieve this effect with a single implementation.

Side effects

In mathematics, a function maps one or more input values to some output value. In computer programming, many functions fit that same model: they accept one or more arguments, and their only purpose is to return a value. A纯函数is a function that, given the same arguments, always return the same value, without producing any observableside effects, such as consuming input, producing output, or otherwise changing the state of the system. So far, in this section we have considered only pure functions.

However, in computer programming it is also useful to define functions that do produce side effects. In fact, we often define functions whose only purpose is to produce side effects. An explicitreturnstatement is optional in such a function: control returns to the caller after Python executes the function’s last statement. Functions with no specified return value actually return the special valueNone, which is usually ignored.

For example, the的头.write()function has the side effect of writing the given argument to standard output (and has no specified return value). Similarly, the following function has the side effect of drawing a triangle to standard drawing (and has no specified return value):

defdrawTriangle(x0, y0, x1, y1, x2, y2): stddraw.line(x0, y0, x1, y1) stddraw.line(x1, y1, x2, y2) stddraw.line(x2, y2, x0, y0)

It is generally poor style to compose a function that both produces side effects and returns a value. One notable exception arises in functions that read input. For example, the的头.readInt()function both returns a value (an integer) and produces a side effect (consuming one integer from standard input).

Type checking

In mathematics, the definition of a function specifies both the domain and the range. For example, for the harmonic numbers, the domain is the positive integers and the range is the positive real numbers. In Python, we do not specify the types of the parameter variables or the type of the return value. As long as Python can apply all of the operations within a function, Python executes the function and returns a value.

If Python cannot apply an operation to a given object because it is of the wrong type, it raises a run-time error to indicate the invalid type. For example, if you call thesquare()function defined earlier with anintargument, the result is anint; if you call it with afloatargument, the result is afloat. However, if you call it with a string argument, then Python raises aTypeErrorat run time.

This flexibility is a popular feature of Python (known aspolymorphism) because it allows us to define a single function for use with objects of different types. It can also lead to unexpected errors when we call a function with arguments of unanticipated types. In principle, we could include code to check for such errors, and we could carefully specify which types of data each function is supposed to work with. Like most Python programmers, we refrain from doing so. However, in this book, our message is thatyou should always be aware of the type of your data, and the functions that we consider in this book are built in line with this philosophy, which admittedly clashes with Python’s tendency toward polymorphism. We will discuss this issue in some detail in SECTION3.3.

THE TABLE BELOW SUMMARIZES OUR DISCUSSIONby collecting together the function definitions that we have examined so far. To check your understanding, take the time to reread these examples carefully.

primality test

defisPrime(n): if n < 2: return False i = 2 while i*i <= n: if n % i == 0: return False i += 1 return True

hypotenuse of a right triangle

defhypot(a, b) return math.sqrt(a*a + b*b)

generalized harmonic number

defharmonic(n, r=1): total = 0.0 for i in range(1, n+1): total += 1.0 / (i ** r) return total

draw a triangle

defdrawTriangle(x0, y0, x1, y1, x2, y2): stddraw.line(x0, y0, x1, y1) stddraw.line(x1, y1, x2, y2) stddraw.line(x2, y2, x0, y0)

Typical code for implementing functions

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

培生提供feedbac可能提供机会k or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

不wsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simplyemailinformation@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through ourContact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on theAccount page. If a user no longer desires our service and desires to delete his or her account, please contact us atcustomer-service@informit.comand we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:www.e-skidka.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to不vadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read ourSupplemental privacy statement for California residents与此同时,注意隐私。的Supplemental privacy statement for California residentsexplains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Pleasecontact usabout this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020