Python function (ii)

Source: Internet
Author: User

Parameters

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

    • Required Parameters
    • Keyword parameters
    • Default parameters
    • Indefinite length parameter
Required Parameters

The required parameters must be passed into the function in the correct order. The number of calls must be the same as when declared.

Call the Printme () function, you must pass in a parameter, or a syntax error will occur:

#!/usr/bin/python#-*-coding:utf-8-*-#可写函数说明def printme():"Print any incoming string"  Print str;  return;  #调用printme函数printme();              

The result of the above example output:

traceback  (most recent call last):  file< Span class= "PLN" >  "test.py" , line 11, in <module>  Printme (); typeerror: Printme () 1 argument  (0  Given) 






Keyword parameters

Keyword arguments are closely related to function calls, and function calls use keyword parameters to determine the values of the parameters passed in.

Using the keyword argument allows a function call when the order of the arguments is inconsistent with the Declaration, because the Python interpreter can match the parameter values with the name of the argument.

The following instance uses the parameter name when the function Printme () is called:

#!/usr/bin/python#-*-Coding:utf-8-*- #可写函数说明DefPrintinfo(Name, age ):   "Print any incoming string" Span class= "PLN" > print  "Name:" , Name;print  "age" , Age return; #调用printinfo函数 printinfo ( age =50, Name=  "Miki"           
Default parameters

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

#!/usr/bin/python#-*-coding:utf-8-*-  #可写函数说明 def Printinfo ( name< Span class= "pun" >, age = 35  ):   "Print any incoming string"  print  "Name:" , Name print  "age" , Age;return             
Printinfo( name="Miki");    

The result of the above example output:

Name: Mikiage35

Indefinite length parameter

You may need a function that can handle more arguments than was originally declared. These parameters are called indeterminate length parameters, and are not named when declared, unlike the above 2 parameters. The basic syntax is as follows:

def functionname([Formal_args,]*):"Function _ Document String"return[expression] 

Variable names with an asterisk (*) will hold all unnamed variable arguments. Choose not to send more parameters can also. The following example:

#!/usr/bin/python#-*-Coding:utf-8-*- # Writable Function DescriptionDefPrintinfo(Arg1, *Vartuple): "Print any parameters passed in" Print "Output:" Print arg1 for var in Vartuple: print  var return;# call printinfo function printinfo ( 10  ( 70, 60, 50    

The result of the above example output:

Output: output:    
anonymous functions

Python uses lambda to create anonymous functions.

    • Lambda is just an expression, and the function body is much simpler than def.
    • The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression.
    • The lambda function has its own namespace and cannot access parameters outside its own argument list or in the global namespace.
    • Although the lambda function appears to be only a single line, it is not equivalent to a C or C + + inline function, which is designed to call small functions without consuming stack memory to increase operational efficiency.
Grammar

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

Lambda[[,arg2,..... argn]]:expression      

The following example:

#!/usr/bin/python#-*-Coding:utf-8-*- # Writable Function DescriptionSum= LambdaArg1, Arg2: arg1 + Arg2 # call the Sum function print , Sum ( 10, 20) print  "Add the following values:" , Sum ( 20 20 )        

The result of the above example output:

The added value is:     The added value is :     
Return statement

Return statement [expression] exits the function, optionally returning an expression to the caller. A return statement without a parameter value returns none. The previous example does not demonstrate how to return a value, and the following example tells you how to do it:

#!/usr/bin/python#-*-Coding:utf-8-*- # Writable Function Descriptiondef Sum ( Arg1, arg2 ):  # returns the of 2 parameters. "  Total = arg1 + arg2 print , Total return Total;# calls the Sum function total = Sum ( Span class= "PLN" > 10, 20              

The result of the above example output:

In function  :    
Variable scope

All variables of a program are not accessible in any location. Access permissions depend on where the variable is assigned.

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

    • Global variables
    • Local variables
Global variables and local variables

Variables defined inside a function have a local scope, which defines the owning global scope outside of the function.

Local variables can only be accessed within their declared functions, while global variables are accessible throughout the program. When a function is called, all variable names declared within the function are added to the scope. The following example:

#!/usr/bin/python#-*-Coding:utf-8-*-Total= 0; # This is a global variable# Writable Function DescriptionDefSum(Arg1,Arg2): #返回2个参数的和. " Total = arg1 + Arg2 # total is here a local variable. print , Total return Total; #调用sum函数 sum ( 10, 20  print  "functions are global variables:" ,                 

Python function (ii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.