预计阅读本页时间:-
def Statements
The def statement creates a function object and assigns it to a name. Its general format is as follows:
def <name>(arg1, arg2,... argN):
<statements>
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
As with all compound Python statements, def consists of a header line followed by a block of statements, usually indented (or a simple statement after the colon). The statement block becomes the function’s body—that is, the code Python executes each time the function is called.
The def header line specifies a function name that is assigned the function object, along with a list of zero or more arguments (sometimes called parameters) in parentheses. The argument names in the header are assigned to the objects passed in parentheses at the point of call.
Function bodies often contain a return statement:
def <name>(arg1, arg2,... argN):
...
return <value>
The Python return statement can show up anywhere in a function body; it ends the function call and sends a result back to the caller. The return statement consists of an object expression that gives the function’s result. The return statement is optional; if it’s not present, the function exits when the control flow falls off the end of the function body. Technically, a function without a return statement returns the None object automatically, but this return value is usually ignored.
Functions may also contain yield statements, which are designed to produce a series of values over time, but we’ll defer discussion of these until we survey generator topics in Chapter 20.