Python basic in...login
Python basic introductory tutorial
author:php.cn  update time:2022-04-18 16:14:50

Python functions


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

Function can improve the modularity of the application and the reuse rate of the code. 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:

  • Function code A block begins 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 documentation string - used to store function descriptions.

  • The function content starts with a colon and is indented.

  • return [expression] End the function and optionally return a value to the caller. Return without an expression is equivalent to returning None.


Syntax

def functionname(parameters):
"Function_docstring"
function_suite
return [ expression]

By default, parameter values ​​and parameter 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 input parameter and then prints it to a standard display device.

def printme(str):
"Print the incoming string to the standard display device"
print str
return

Function call

Defining a function only gives 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
# -*- coding: UTF-8 -*-

# Define function
def printme(str):
"Print any incoming string"
print str;
return;

# Call function
printme("I want to call a user-defined function!");
printme("Call the same function again");

The output result of the above example:

I want to call a user-defined function!
Call the same function again

Passing parameters by value and passing parameters by reference

All parameters (independent variables) are passed by reference in Python. 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
# -*- coding: UTF-8 -*-

# Writable function description
def changeme ( mylist ):
"Modify the incoming list"
mylist.append([1,2,3,4]);
print "Value within the function: ", mylist
return

# Call the 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

  • Keyword parameters

  • Default parameters

  • Variable length Parameters

Required 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
# -*- coding : UTF-8 -*-

#Writable function description
def printme(str):
"Print any incoming string"
print str;
return;

#Call printme function
printme();

The above example output result:

Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

Keyword parameters

Keyword parameters are closely related to function calls. Function calls use keyword parameters to determine the incoming parameter values.

Using keyword arguments allows the function to be called in a different order than when it was declared, because the Python interpreter can match parameter names with parameter values.

The following examples use parameter names when calling function printme():

#!/usr/bin/python
# -*- coding: UTF-8 -* -

#Writable function description
def printme(str):
"Print any incoming string"
print str;
return;

#Call the printme function
printme(str = "My string");

The above example output result:

My string

The following example can show more clearly that the order of keyword parameters is not important:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

#Writable function description
def printinfo(name, age):
"Print any incoming string"
print "Name: ", name;
print "Age " , age;
return;

#Call the printinfo function
printinfo(age=50, name="miki");

The above example output result:

Name: miki
Age 50

Default parameters

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

#!/usr/bin/python
# -*- coding: UTF-8 -*-

#Writable function description
def printinfo(name, age = 35):
"Print any incoming string"
print "Name: ", name;
print "Age " , age;
return;

#Call printinfo function
printinfo( age=50, name="miki" );
printinfo( name="miki" );

Output result of the above example:

Name: miki
Age 50
Name: miki
Age 35

Indefinite length parameters

You may need a function that can handle more parameters than when 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_Documentation String"
function_suite
return [expression]

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

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# Writable function description
def printinfo(arg1, *vartuple):
"Print any passed arguments"
print "Output: "
print arg1
for var in vartuple:
print var
return;

# Call the printinfo function
printinfo( 10 );
printinfo( 70, 60, 50 );

The above example output result:

Output:
10
Output:
70
60
50

Anonymous function

python uses lambda to Create anonymous functions.

  • lambda is just an expression, and the function body is much simpler than def.

  • The body of lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions.

  • 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 a small function without occupying stack memory and thereby increasing the execution time. 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
# -*- coding: UTF-8 -*-

# Writable function description
sum = lambda arg1, arg2: arg1 + arg2;

# Call the sum function
print "The added value is: ", sum ( 10, 20 )
print "The added value is : ", sum( 20, 20 )

The above example output result:

Add The value after adding is: 30
The value after adding is: 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
# -*- coding: UTF-8 -*-

# Writable function description
def sum( arg1, arg2 ):
# Returns the sum of 2 parameters. "
total = arg1 + arg2
print "Inside the function: ", total
return total;

# Call the sum function
total = sum(10, 20);
print "Outside the function: ", total

Output results of the above example:

Inside the function: 30
Outside the function: 30

##Variable scope

of a program Not all variables are accessible at all locations. Access permissions depend on where the variable is assigned.