Python Functions
A function is an organized, reusable block of code that implements a single or related set of functions.
Functions improve the modularity of applications and the reuse of code. You already know that Python provides many built-in functions such as print(). But you can also create your own functions; these are called user-defined functions.
Defining a function
You can define a function with the functionality you want; here are the simple rules:
- A function code block begins with the def begins with the keyword, followed by the function identifier name and parentheses **().**
- Any incoming parameters and arguments must be placed between the parentheses. Parameters can be defined between the parentheses.
- The first statement of a function may optionally use a docstring - used to store the function description.
- The function body begins with a colon and is indented.
- return [expression] ends the function, optionally returning a value to the caller. A return without an expression is equivalent to returning None.
Syntax
def
functionname
(
parameters
)
:
"
Function docstring
"
function_suite
return
[
expression
]
By default, parameter values and names are matched in the order defined in the function declaration.
Example
The following is a simple Python function that takes a string as an argument and prints it to the standard output device.
Example (Python 2.0+)
def
printme
(
str
)
:
"
Print the passed string to the standard output device
"
str
return
Function call
Defining a function only gives it a name, specifies the parameters it contains, and defines the code block structure.
Once the basic structure of the function is complete, you can execute it by calling it from another function or directly from the Python prompt.
The following example calls the printme() function:
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
Defining a function
def
printme
(
str
)
:
"
Print any string passed in
"
str
return
Calling a function
printme
(
"
I am calling a user-defined function!
"
)
printme
(
"
Call the same function again
"
)
The example above produces the following output:
我要调用用户自定义函数!
再次调用同一函数
to the parameter
In Python, types belong to objects, and variables have no type:
a
=
[
1
,
2
,
3
]
a
=
"
Runoob
"
In the code above,[1,2,3] is of type List,"Runoob" is of type String, while variable a has no type; it is merely a reference to an object (a pointer), which can be a List object or point to a String object.
Mutable and immutable objects
In Python, strings, tuples and numbers are immutable objects, while list, dict and others are modifiable objects.
-
Immutable types:Variable assignment a=5 then assign again a=10, here a new int value object 10 is actually created, and a is made to point to it, while 5 is discarded. This does not change the value of a; it is equivalent to creating a new a.
-
Mutable types:Variable assignment la=[1,2,3,4] then assign again la[2]=5 changes the value of the third element of list la; la itself is untouched, only part of its internal values is modified.
Parameter passing in Python functions:
-
Immutable types:Similar to pass-by-value in C++, as with integers, strings, and tuples. For example, with fun(a), only the value of a is passed, which does not affect the object a itself. For instance, modifying the value of a inside fun(a) only modifies another copied object and does not affect a itself.
-
Mutable types:Similar to pass-by-reference in C++, as with lists and dictionaries. For example, with fun(la), la is truly passed through, and after modification the la outside fun is also affected
Everything in Python is an object; strictly speaking we cannot talk about pass-by-value or pass-by-reference, but should speak of passing immutable objects and passing mutable objects.
Example of passing an immutable object in Python
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
def
ChangeInt
(
a
)
:
a
=
10
b
=
2
ChangeInt
(
b
)
b
The result is 2
In the example there is an int object 2, and the variable pointing to it is b. When passed to the ChangeInt function, variable b is copied by value, and both a and b point to the same Int object. When a=10, a new int value object 10 is created and a is made to point to it.
Example of passing a mutable object
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
Function description can be written
def
changeme
(
mylist
)
:
"
Modify the list passed in
"
mylist
.
append
(
[
1
,
2
,
3
,
4
]
)
"
Values inside the function:
"
,
mylist
return
Call the changeme function
mylist
=
[
10
,
20
,
30
]
changeme
(
mylist
)
"
Values outside the function:
"
,
mylist
In the example, the object passed into the function and the object to which new content is appended at the end use the same reference, so the output is as follows:
函数内取值: [10, 20, 30, [1, 2, 3, 4]]
函数外取值: [10, 20, 30, [1, 2, 3, 4]]
Parameters
The following are the formal parameter types available when calling a function:
- Required parameters
- Keyword arguments
- Default arguments
- Variable-length arguments
Required parameters
Required parameters must be passed to the function in the correct order. The number of arguments at call time must match the number at declaration.
To call the printme() function, you must pass an argument, otherwise a syntax error occurs:
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
# Function description can be written
def
printme
(
str
)
:
"
Print any string passed in
"
str
return
# Call the printme function
printme
(
)
The example above produces the following output:
Traceback (most recent call last):
File "test.py", line 11, in
printme()
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are closely tied to function calls; a call uses keyword arguments to determine the values passed in.
Keyword arguments allow the order of arguments at call time to differ from the declaration, because the Python interpreter can match values using parameter names.
The following example uses parameter names when calling the printme() function:
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
# Function description can be written
def
printme
(
str
)
:
"
Print any string passed in
"
str
return
# Call the printme function
printme
(
str
=
"
My string
"
)
The example above produces the following output:
My string
The following example shows more clearly that the order of keyword arguments does not matter:
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
# Function description can be written
def
printinfo
(
name
,
age
)
:
"
Print any string passed in
"
"
Name:
"
,
name
"
Age
"
,
age
return
# Call the printinfo function
printinfo
(
age
=
50
,
name
=
"
miki
"
)
The example above produces the following output:
Name: miki
Age 50
Default arguments
When calling a function, if a value for a default parameter is not passed, the default value is used. The following example prints the default age if age is not passed:
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
# Function description can be written
def
printinfo
(
name
,
age
=
35
)
:
"
Print any string passed in
"
"
Name:
"
,
name
"
Age
"
,
age
return
# Call the printinfo function
printinfo
(
age
=
50
,
name
=
"
miki
"
)
printinfo
(
name
=
"
miki
"
)
The example above produces the following output:
Name: miki
Age 50
Name: miki
Age 35
Variable-length arguments
You may need a function that can handle more arguments than were originally declared. These are called variable-length arguments. Unlike the two types of parameters above, they are not named at declaration. The basic syntax is as follows:
def
functionname
(
[
formal_args
,
]
var_args_tuple
)
:
"
Function docstring
"
function_suite
return
[
expression
]
A variable name prefixed with an asterisk (*) stores all unnamed variable arguments. An example of variable-length arguments is as follows:
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
Function description can be written
def
printinfo
(
arg1
, *
vartuple
)
:
"
Print any arguments passed in
"
"
Output:
"
arg1
for
var
in
vartuple
:
var
return
Call the printinfo function
printinfo
(
10
)
printinfo
(
70
,
60
,
50
)
The example above produces the following output:
输出:
10
输出:
70
60
50
Anonymous functions
Python uses lambda to create anonymous functions.
- lambda is just an expression, and its function body is much simpler than a def.
- The body of a lambda is an expression, not a code block. Only limited logic can be encapsulated in a lambda expression.
- A lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace.
- Although a lambda function appears to be written on a single line, it is not equivalent to an inline function in C or C++, whose purpose is to avoid using stack memory when calling small functions, thereby increasing runtime efficiency.
Syntax
The syntax of a lambda function contains only a single statement, as follows:
lambda [arg1 [,arg2,.....argn]]:expression
The following example:
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
Function description can be written
sum
=
lambda
arg1
,
arg2
:
arg1
arg2
Call the sum function
"
The value after addition is :
"
,
sum
(
10
,
20
)
"
The value after addition is :
"
,
sum
(
20
,
20
)
The example above produces the following output:
相加后的值为 : 30
相加后的值为 : 40
The return statement
The return statement [expression] exits a function, optionally returning an expression to the caller. A return statement without a value returns None. None of the previous examples showed how to return a value; the following example shows you how:
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
Function description can be written
def
sum
(
arg1
,
arg2
)
:
Return the sum of 2 arguments."
total
=
arg1
arg2
"
Inside the function :
"
,
total
return
total
Call the sum function
total
=
sum
(
10
,
20
)
The example above produces the following output:
函数内 : 30
Variable scope
Not all variables in a program are accessible from every location. Access permission depends on where the variable is assigned.
- Global Variables
- local variables
Global and local variables
Variables defined inside a function have a local scope; those defined outside have a global scope.
Local variables can only be accessed within the function in which they are declared, while global variables can be accessed throughout the entire program. When a function is called, all variable names declared within it are added to the scope. As in the following example:
Example (Python 2.0+)
The example above produces the following output:
函数内是局部变量 : 30 函数外是全局变量 : 0