Home  >  Article  >  Backend Development  >  Python functions

Python functions

高洛峰
高洛峰Original
2016-11-23 10:38:171121browse

Function is an organized, reusable code segment used to implement a single or related function.

Functions can improve application modularity and code reuse. You already know that Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.

Define a function

You can define a function with the functions you want, the following are simple rules:

The function code block starts with the def keyword, followed by the function identifier name and parentheses ().

Any incoming parameters and independent variables must be placed between parentheses. Parameters can be defined between parentheses.

The first line of a function can optionally use a docstring - used to store function descriptions.

Function content starts with a colon and is indented.

Return[expression] ends the function and optionally returns a value to the caller. Return without an expression is equivalent to returning None.

Syntax

def functionname(parameters):

"Function_docstring"

function_suite

return [expression]

Default case, parameter values ​​and parameter names are by The order of definitions in the function declaration matches.

Example

The following is a simple Python function that takes a string as an input parameter and prints it to a standard display device.

def printme(string):

"Print the incoming string to a standard display device"

print string

Function call

Define a function and only give the function a name , specifies the parameters contained in the function, and the code block structure.

After the basic structure of this function is completed, you can execute it through another function call or directly from the Python prompt.

The following example calls the printme() function:

#!/usr/bin/python

# Function definition is here

def printme( string ):

"Print any incoming String"

print string

# Now you can call printme function

printme("I want to call a user-defined function!");

printme("Call the same function again");

Output result of the above example:

I want to call a user-defined function!

Call the same function again

Pass parameters by value and pass parameters by reference

All parameters (independent variables) In Python everything is passed by reference. If you change the parameters in the function, the original parameters will also be changed in the function that calls this function. For example:

#!/usr/bin/python

# Writable function description

def changeme( mylist ):

"Modify the incoming list"

mylist.append([1 ,2,3,4])

print "Value in function: ", mylist

# Call changeme function

mylist = [10,20,30];

changeme( mylist );

print "Value outside the function: ", mylist

The object passed into the function and the object to add new content at the end use the same reference. Therefore, the output result is as follows:

Values ​​within the function: [10, 20, 30, [1, 2, 3, 4]]

Values ​​outside the function: [10, 20, 30, [1, 2, 3, 4]]

Parameters

The following are the formal parameter types that can be used when calling functions:

Required parameters

Named parameters

Default parameters

Variable length parameters

Required Preparatory parameters

Required parameters must be passed into the function in the correct order. The quantity when called must be the same as when declared.

When calling the printme() function, you must pass in a parameter, otherwise a syntax error will occur:

#!/usr/bin/python

#Writable function description

def printme( string ):

"Print any incoming string"

print string

#Call the printme function

printme()

The output result of the above example:

Traceback (most recent call last):

File "test.py", line 11, in

printme()

TypeError: printme() takes exactly 1 argument (0 given)

named parameters

Named parameters are closely related to function calls. The caller uses the naming of parameters to determine the value of the parameters passed in. You can skip unpassed parameters or pass parameters out of order because the Python interpreter can match parameter names with parameter values. Call the printme() function with named parameters:

#!/usr/bin/python

#Writable function description

def printme( string ):

"Print any incoming string "

 print string

#Call the printme function

printme(str = "My string")

The output result of the above example:

My string

next The example can show more clearly that the order of named parameters is not important:

#!/usr/bin/python

#Writable function description

def printinfo(name, age):

"Print Any incoming string "

print "Name: ", name

print "Age ", age

#Call the printinfo function

printinfo(age=50, name="miki" )

Output result of the above example:

Name: miki

Age 50

Default parameters

When calling a function, if the value of the default parameter is not passed in, it is considered to be the default value. The following example will print the default age, if age is not passed in:

#!/usr/bin/python

#Writable function description

def printinfo(name, age = 35):

"Print any incoming string"

print "Name: ", name

print "Age ", age

#Call the printinfo function

printinfo(age=50, name="miki")

printinfo(name="miki")

The output result of the above example:

Name: miki

Age 50

Name: miki

Age 35

Indeterminate length Parameters

You may need a function that can handle more parameters than originally declared. These parameters are called variable-length parameters. Unlike the above two parameters, they will not be named when declared. The basic syntax is as follows:

def functionname([formal_args,] *var_args_tuple ):

"Function_docstring"

function_suite

return [expression]

Starred ( *) variable names will store all unnamed variable parameters. You can also choose not to pass more parameters. The following example:

#!/usr/bin/python

# Writable function description

def printinfo(arg1, *vartuple):

"Print any incoming parameters"

print "Output: "

print arg1

for var in vartuple:

print var

# Call printinfo function

printinfo(10)

printinfo(70, 60, 50 )

and above Example output result:

Output:

10

Output:

70

60

50

Anonymous function

Use lambda keyword Ability to create small anonymous functions. This type of function gets its name from the fact that the standard step of declaring a function with def is omitted.

Lambda function can receive any number of parameters but can only return the value of one expression, and it cannot contain commands or multiple expressions.

Anonymous functions cannot call print directly because lambda requires an expression.

The lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace.

Although the lambda function seems to only be able to write one line, it is not equivalent to the inline function of C or C++. The purpose of the latter is to call small functions without occupying stack memory and thus increase operating efficiency.

Grammar

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

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

The following example:

#!/usr/bin/python

#Writable function description

sum = lambda arg1, arg2: arg1 + arg2

#Call the sum function

print "Value of total" : " , sum( 10, 20 )

print "Value of total : ", sum( 20, 20 )

The above example output result:

Value of total : 30

Value of total : 40

return statement

return statement [expression] exits the function and optionally returns an expression to the caller. A return statement without parameter values ​​returns None. The previous examples did not demonstrate how to return a value. The following example will tell you how to do it:

#!/usr/bin/python

#Writable function description

def sum( arg1, arg2 ) ; total = sum( 10, 20 );

print "Outside the function : ", total

The above example output result:

Inside the function : 30

Outside the function : 30

Variables Scope

Not all variables in a program can be accessed everywhere. Access permissions depend on where the variable is assigned.

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

global variables

local variables

variables and local variables

Variables defined inside a function have a local scope, and variables defined outside the function have a global scope Scope.

Local variables can only be accessed within the function in which they are declared, while global variables can be accessed within the entire program scope. When a function is called, all variable names declared within the function will be added to the scope. The following example:

#!/usr/bin/python

total = 0; #Return the sum of the 2 parameters. "

total = arg1 + arg2; # total is a local variable here.

print "Inside the function local total : ", total

return total;

#Call sum Function

sum( 10, 20 );

print "Outside the function global total : ", total

The above example output result:

Inside the function local total : 30

Outside the function global total : 0

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Python modulesNext article:Python modules