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

Python Functions

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:


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

"

print

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

"

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, 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.

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

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

def

ChangeInt

(

a

)

:

a

=

10

b

=

2

ChangeInt

(

b

)

print

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

]

)

print

"

Values inside the function:

"

,

mylist

return

Call the changeme function

mylist

=

[

10

,

20

,

30

]

changeme

(

mylist

)

print

"

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

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

"

print

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

"

print

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

"

print

"

Name:

"

,

name

print

"

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

"

print

"

Name:

"

,

name

print

"

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

"

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

Anonymous functions

Python uses lambda to create anonymous functions.

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

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

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

print

"

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.

The scope of a variable determines which part of the program can access a particular variable name. The two most basic variable scopes are as follows:

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

#!/usr/bin/python # -*- coding: UTF-8 -*- total = 0 # This is a global variable # Writable function description def sum( arg1, arg2 ): # Return the sum of 2 arguments." total = arg1 + arg2 # total is a local variable here. print "Inside the function it is a local variable : ", total return total # Call the sum function sum( 10, 20 ) print "Outside the function it is a global variable : ", total

The example above produces the following output:

函数内是局部变量 :  30
函数外是全局变量 :  0