Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 Functions

Python3 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:


Syntax

Python defines functions with the def keyword; the general format is as follows:


def 函数名(参数列表):
    函数体

By default, parameter values and names are matched in the order defined in the function declaration.

Example

Let us use a function to output "Hello World!":

#!/usr/bin/python3

def

hello

(

)

:

   

print

(

"Hello World!"

)

hello

(

)

A slightly more complex application, with parameter variables in the function:

Example (Python 3.0+)

Compare two numbers and return the larger one:

#!/usr/bin/python3

def

max

(

a

,

b

)

:

if

a

b

:

return

a

else

:

return

b

a

=

4

b

=

5

print

(

max

(

a

,

b

)

)

The example above produces the following output:


5

Example (Python 3.0+)

Function to compute an area:

#!/usr/bin/python3

Function to compute an area

def

area

(

width

,

height

)

:

return

width

height

def

print_welcome

(

name

)

:

print

(

"

Welcome

"

,

name

)

print_welcome

(

"

Runoob

"

)

w

=

4

h

=

5

print

(

"

width =

"

,

w

,

"

height =

"

,

h

,

"

area =

"

,

area

(

w

,

h

)

)

The example above produces the following output:


Welcome Runoob
width = 4  height = 5  area = 20

Function call

Defining a function gives it a name, specifies the parameters it contains and the structure of its code block.

Once this basic structure is complete, you can execute it by calling it from another function, or directly from the Python command prompt.

The following example calls printme() functions as follows:

Example (Python 3.0+)

#!/usr/bin/python3

Defining a function

def

printme

(

str

)

:

Print any string passed in

print

(

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; objects are distinguished by different types, while 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 the variable a has no type; it is merely a reference (a pointer) to an object, which can point to an object of type List or to an object of type String.

Mutable and immutable objects

In Python, strings, tuples and numbers are immutable objects, while list, dict and others are modifiable objects.

Parameter passing in Python functions:

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

Pass id() function to observe the change of the memory address:

Example (Python 3.0+)

def

change

(

a

)

:

print

(

id

(

a

)

)

They point to the same object

a

=

10

print

(

id

(

a

)

)

A new object

a

=

1

print

(

id

(

a

)

)

change

(

a

)

The output of the above example is:

4379369136
4379369136
4379369424

You can see that before and after calling the function, the formal and actual arguments point to the same object (the same object id); after modifying the formal argument inside the function, it points to a different id.

Example of passing a mutable object

If a mutable object's parameter is modified inside a function, the original parameter in the calling function is changed as well. For example:

Example (Python 3.0+)

#!/usr/bin/python3

Function description can be written

def

changeme

(

mylist

)

:

"

Modify the list passed in

"

mylist

.

append

(

[

1

,

2

,

3

,

4

]

)

print

(

"

Values inside the function:

"

,

mylist

)

return

Call the changeme function

mylist

=

[

10

,

20

,

30

]

changeme

(

mylist

)

print

(

"

Values outside the function:

"

,

mylist

)

The object passed into the function and the one with new content appended at the end use the same reference. The output is therefore 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 arguments

Required arguments must be passed to the function in the correct order. The number at call time must match the declaration.

When calling the printme() function, you must pass one argument, otherwise a syntax error occurs:

Example (Python 3.0+)

#!/usr/bin/python3

# Function description can be written

def

printme

(

str

)

:

"

Print any string passed in

"

print

(

str

)

return

Calling the printme function without an argument raises an error

printme

(

)

The example above produces the following output:


Traceback (most recent call last):
  File "test.py", line 10, in 
    printme()
TypeError: printme() missing 1 required positional argument: 'str'

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 3.0+)

#!/usr/bin/python3

# Function description can be written

def

printme

(

str

)

:

"

Print any string passed in

"

print

(

str

)

return

# Call the printme function

printme

(

str

=

"

Runoob Tutorial

"

)

The example above produces the following output:


Runoob Tutorial

The following example shows that function arguments need not be used in a specified order:

Example (Python 3.0+)

#!/usr/bin/python3

# Function description can be written

def

printinfo

(

name

,

age

)

:

"

Print any string passed in

"

print

(

"

Name:

"

,

name

)

print

(

"

Age:

"

,

age

)

return

# Call the printinfo function

printinfo

(

age

=

50

,

name

=

"

runoob

"

)

The example above produces the following output:


名字:  runoob
年龄:  50

Default arguments

When calling a function, if no argument is passed, the default argument is used. In the following example, if the age argument is not passed, its default value is used:

Example (Python 3.0+)

#!/usr/bin/python3

# Function description can be written

def

printinfo

(

name

,

age

=

35

)

:

"

Print any string passed in

"

print

(

"

Name:

"

,

name

)

print

(

"

Age:

"

,

age

)

return

# Call the printinfo function

printinfo

(

age

=

50

,

name

=

"

runoob

"

)

print

(

"


"

)

printinfo

(

name

=

"

runoob

"

)

The example above produces the following output:


名字:  runoob
年龄:  50
------------------------
名字:  runoob
年龄:  35

Variable-length arguments

You may need a function that can handle more arguments than were declared. These are called variable-length arguments; unlike the two types above, they are not named in the declaration. The basic syntax is as follows:


def functionname([formal_args,] *var_args_tuple ):
   "函数_文档字符串"
   function_suite
   return [expression]

Parameters prefixed with an asterisk * are imported as a tuple, holding all unnamed variable arguments.

Example (Python 3.0+)

#!/usr/bin/python3

Function description can be written

def

printinfo

(

arg1

, *

vartuple

)

:

"

Print any arguments passed in

"

print

(

"

Output:

"

)

print

(

arg1

)

print

(

vartuple

)

Call the printinfo function

printinfo

(

70

,

60

,

50

)

The example above produces the following output:

输出: 
70
(60, 50)

If no argument is specified at call time, it is an empty tuple. We can also pass no unnamed variables to the function. For example:

Example (Python 3.0+)

#!/usr/bin/python3

Function description can be written

def

printinfo

(

arg1

, *

vartuple

)

:

"

Print any arguments passed in

"

print

(

"

Output:

"

)

print

(

arg1

)

for

var

in

vartuple

:

print

(

var

)

return

Call the printinfo function

printinfo

(

10

)

printinfo

(

70

,

60

,

50

)

The example above produces the following output:


输出:
10
输出:
70
60
50

There is also the case of parameters with two asterisks **; the basic syntax is as follows:


def functionname([formal_args,] **var_args_dict ):
   "函数_文档字符串"
   function_suite
   return [expression]

Parameters prefixed with two asterisks ** are imported as a dictionary.

Example (Python 3.0+)

#!/usr/bin/python3

Function description can be written

def

printinfo

(

arg1

, **

vardict

)

:

"

Print any arguments passed in

"

print

(

"

Output:

"

)

print

(

arg1

)

print

(

vardict

)

Call the printinfo function

printinfo

(

1

,

a

=

2

,

b

=

3

)

The example above produces the following output:


输出: 
1
{'a': 2, 'b': 3}

When declaring a function, an asterisk * can appear alone among the parameters, for example:

def f(a,b,*,c):
    return a+b+c

If an asterisk * appears alone, the parameters after it must be passed as keyword arguments:

>>> def f(a,b,*,c):
...     return a+b+c
... 
>>> f(1,2,3)   # 报错
Traceback (most recent call last):
  File "", line 1, in 
TypeError: f() takes 2 positional arguments but 3 were given
>>> f(1,2,c=3) # 正常
6
>>>

Anonymous functions

Python uses lambda to create anonymous functions.

Anonymous means no longer using the def statement, the standard form for defining a function.

Syntax

The syntax of a lambda function contains only one statement, as follows:


lambda [arg1 [,arg2,.....argn]]:expression

Set parameter a plus 10:

Example

x

=

lambda

a

:

a

10

print

(

x

(

5

)

)

The example above produces the following output:

15

The following example sets two parameters on an anonymous function:

Example (Python 3.0+)

#!/usr/bin/python3

Function description can be written

sum

=

lambda

arg1

,

arg2

:

arg1

arg2

Call the sum function

print

(

"

The value after addition is :

"

,

sum

(

10

,

20

)

)

print

(

"

The value after addition is :

"

,

sum

(

20

,

20

)

)

The example above produces the following output:


相加后的值为 :  30
相加后的值为 :  40

We can wrap an anonymous function inside a function, so the same code can create multiple anonymous functions.

The following example wraps an anonymous function inside myfunc, creating different anonymous functions by passing different arguments:

Example

def

myfunc

(

n

)

:

return

lambda

a

:

a

n

mydoubler

=

myfunc

(

2

)

mytripler

=

myfunc

(

3

)

print

(

mydoubler

(

11

)

)

print

(

mytripler

(

11

)

)

The example above produces the following output:


22
33

For more on anonymous functions, see also:Python lambda (Anonymous Function)


The return statement

return [expression] statement is used to exit a function, optionally returning an expression to the caller. A return statement with no value returns None. None of the previous examples showed how to return a value; the following example demonstrates the return statement:

Example (Python 3.0+)

#!/usr/bin/python3

Function description can be written

def

sum

(

arg1

,

arg2

)

:

Return the sum of 2 arguments."

total

=

arg1

arg2

print

(

"

Inside the function :

"

,

total

)

return

total

Call the sum function

total

=

sum

(

10

,

20

)

print

(

"

Outside the function :

"

,

total

)

The example above produces the following output:


函数内 :  30
函数外 :  30

Positional-only parameters

Python 3.8 added the function parameter syntax / to indicate that function parameters must be passed positionally and cannot be passed as keyword arguments.

In the following example, parameters a and b must be positional-only, c or d can be positional or keyword parameters, and e and f are required to be keyword parameters:

def f(a, b, /, c, d, *, e, f):
    print(a, b, c, d, e, f)

The following usage is correct:

f(10, 20, 30, d=40, e=50, f=60)

The following usage produces an error:

f(10, b=20, c=30, d=40, e=50, f=60)   # b 不能使用关键字参数的形式
f(10, 20, 30, 40, 50, f=60)           # e 必须使用关键字参数的形式