Python BASICS (13): functions, 2015 python
A function is a programming method that structured or procedural the program logic.
Python function return value
If nothing is returned, None is returned.
Like most languages, Python returns a value or object. Only when the container object is returned, it looks like multiple objects are returned.
In this way, the operation is flexible, although it is simply an object.
Call a function
We use a pair of parentheses for electrophoresis. Any input parameters should be placed in brackets.
Keyword Parameter
This concept is for function calls. For example, we have such a function.
def fun(value, count): fun_suite
We can call the following code:
fun(12,20)
You can also use keywords to call
fun(value = 12, count = 20)
Or
fun(count = 20, value =12)
In this way, you can enrich the calling methods. You can also use the keyword parameter when the parameter allows "missing. This depends on the default parameters of the function.
Parameter Group
Python also allows programmers to execute a function without explicitly defining parameters. The corresponding method is to pass the tuples or dictionaries as parameters to the function (the tuples are non-Keyword calls, dictionary is called by keyword ). Basically, you can put all parameters into a single tuple or dictionary, and use only these containers containing parameters to call a function without explicitly placing them in the function call:
func(*tuple_grp_nonkw_args, **dict_grp_kw_args)
Here, tuple_grp_nonkw_args is a non-Keyword parameter group in the form of tuples, and dict_grp_kw_args is a dictionary containing keyword parameters. This feature allows you to place variables in tuples and/or dictionaries and call functions without explicitly declaring parameters one by one.
Of course, the following parameters can also be provided:
func(positional_args, keyword_args,*tuple_grp_nonkw_args, **dict_grp_kw_args)
All parameters of this syntax are optional. Each parameter is independent when a single function is called. It can effectively replace the apply () built-in functions before Python1.6.
For example:
From operator import add, subfrom random import randint, choiceops = {'+': add, '-': sub} MAXTRIES = 2def doprob (): op = choice ('+-') nums = [randint (1, 10) for I in range (2)] nums. sort (reverse = True) ans = ops [op] (* nums) # * indicates that this variable is a tuples, the prefix operator pr = '% d % s % d =' % (nums [0], op, nums [1]) oops = 0 while True: try: if int (raw_input (pr) = ans: print 'correct' break if oops = MAXTRIES: print 'answer \ N % s % d' % (pr, ans) else: print 'encrect... try again 'oops + = 1 T (KeyboardInterrupt, \ EOFError, ValueError): print 'invalid input... try again 'def main (): while True: doprob () try: opt = raw_input ('again? [Y] '). lower () if opt and opt [0] = 'N': break t (KeyboardInterrupt, EOFError): breakif _ name _ = '_ main __': main ()
The line with the comment above should be written as apply (ops [op], nums) before Python1.6, instead of ops [op] (* nums)
Create a function
Def statement
Syntax:
def function_name(arguments): "function_documentation_string" function_body_suite
For forward reference, you must define the function before use.
Function attribute
Relationship between namespaces and scopes
You can obtain any namespace in each Python module, class, and function. It can be a variable named x in module foo and bar, but these two variables can still be used after the two modules are imported into your program. Therefore, even if the same variable name is used in the two modules, it is safe because the period attribute identifier has different namespaces for the two modules. For example, there is no name conflict in this Code:
import foo, barprint foo.x + bar.x
Function attribute is another field in Python that uses the period attribute identifier and has a namespace.
The relationship between namespace and scope is described in detail in the previous part of the note module.
Embedded Functions
Creating another function (object) in the function body is completely legal. This type of function is called an internal/Embedded function. Because Python now supports static nested domains, internal functions are actually very useful.
The most obvious method to create internal functions is to define functions in the definition body of external functions, such:
def foo(): def bar(): print 'bar() called' print 'foo() called' bar()foo()bar()
The result is:
foo() calledbar() calledTraceback (most recent call last):File "<pyshell#6>", line 1, in <module>bar()NameError: name 'bar' is not defined
Transfer Function
Similar to other objects, Python functions can be referenced, passed in as parameters, and used as elements of list, dictionary, and other container objects.
A function has a unique feature that distinguishes it from other objects, that is, the function is callable.
Because all objects are passed through references, and functions are no exception. When a variable is assigned a value, the reference of the same object is actually assigned to this variable. If the object is a function, all aliases of this object are callable.
>>> def foo():print 'in foo()'>>> bar = foo>>> bar<function foo at 0x02B3A0B0>>>> bar()in foo()>>> bar = foo()in foo()>>> bar>>> print bar
When we assign foo to bar, bar and foo reference the same function object, so they can be called in the same way as foo. Foo is a reference to a function object, AND foo () is a call to a function object.
At the same time, the function can also be passed into other functions as parameters for calling.
>>> def bar(func):func()>>> bar(foo)in foo()
Note that the reference of a function object is used as a parameter rather than a function object call.
Format parameters
The form parameter set of a Python function is composed of all parameters that need to be passed into the function during the call. This parameter is precisely matched with the parameter list in the function declaration. These parameters include all necessary parameters (Pass in the function in the correct positioning order if it is a standard call, not necessarily in order if it is a keyword call) and all parameters with default values, you do not need to specify parameters when calling a function. (Created when the function is declared) the local namespace is a parameter value and a name is created. Once the function is executed, the name can be accessed.
Location parameters
Location parameters must be passed in the exact order defined in the bewilder call function. In addition, if no default parameter exists, the exact number of input function parameters must be the same as the declared number. Location parameters are the standard parameters we are familiar.
Default parameters
For default parameters, if we do not provide a value when calling a function, the defined standard value is used in advance, as shown below:
>>> def taxMe(cost, rate=0.0825):return cost + (cost * rate)>>> taxMe (100)108.25>>> taxMe (100, 0.05)105.0
Default parameters increase program robustness to a very high level because they supplement some flexibility not provided by standard location parameters.
When we declare, all required parameters must be before the default parameters. Otherwise, in mixed mode, the interpreter cannot know how to match the parameter. Of course, if you use keyword parameters, you can change the order, provided that all parameters that do not have the default value are passed in.
Variable Length Parameters
Functions may need to process variable parameters. You can use a variable-length parameter list. Variable-length parameters are not explicitly named in the function declaration, because the number of parameters is unknown at runtime, which is significantly different from the conventional parameters (location and default, bed cabinet parameters are all named in the function declaration. Because function calls provide two parameter types: keyword and non-Keyword, Python supports variable length parameters in two ways.
Variable Length Parameter (tuples)
When a function is called, all the form parameters (required and default) are assigned to the corresponding local variables in the function declaration.
The remaining non-Keyword parameters are inserted into a single tuples in order for easy access. When calling a function, Python can accept an indefinite number of parameters.
The variable length parameter tuples must follow the positions and default parameters. The function syntax with tuples (or non-Keyword variable length parameters) is as follows:
def function_name([formal_args,] *vargs_tuple): 'function_documentation_string' function_body_suite
After the asterisks operator, the parameters are transmitted as tuples to the function. The tuples store all the "extra" parameters passed to the function (matching all locations and the remaining parameters after the named parameters ). If no additional parameter is provided, the tuples are empty.
In our previous function calls, if an incorrect number of function parameters is given, a TypeError exception is generated. By adding a variable in the Variable Parameter List at the end, we can handle the case where more parameters are passed into the function, because all the extra parameters (non-Keyword) parameters are added to the variable parameter tuples. The same reason as the location parameter must be placed before the keyword parameter. All formal parameters must appear before informal parameters.
def tupleVarArgs(arg1, arg2 = 'defaultB', *theRest): 'display regular args and non-keyword variable args' print 'formal arg 1:', arg1 print 'formal arg 2:', arg2 for eachXtrArg in theRest: print 'another arg:', eachXtrArg
The running result is as follows:
>>> tupleVarArgs('abc')formal arg 1: abcformal arg 2: defaultB>>> tupleVarArgs(23,4.56)formal arg 1: 23formal arg 2: 4.56>>> tupleVarArgs('abc',123,'xyz',456.789)formal arg 1: abcformal arg 2: 123another arg: xyzanother arg: 456.789
Keyword variable parameter (dictionary)
When we have a keyword of an indefinite number or additional set, the parameter is put into a dictionary. The key in the dictionary is the parameter name and the value is the corresponding parameter value.
Syntax:
def function_name([formal_args,][*vargst,] **theRest): function_documentation_string function_body_suite
Double Star numbers (**) are used to distinguish keyword parameters from non-informal parameters (**). ** The overloaded side is not confused with power operations. The keyword variable parameter should be the last parameter defined by the function, **. For example:
>>> def dictVarArgs(arg1,arg2='defaultB',**theRest): 'display 2 regular args and keyword variable args' print 'formal arg1:', arg1 print 'formal arg2:', arg2 for eachXtrArg in theRest.keys(): print 'Xtra arg %s: %s' %\ (eachXtrArg, str (theRest[eachXtrArg]))>>> dictVarArgs(1220,740.0,c='grail')formal arg1: 1220formal arg2: 740.0Xtra arg c: grail>>> dictVarArgs(arg2='tales', c=123, d='poe', arg1='mystery')formal arg1: mysteryformal arg2: talesXtra arg c: 123Xtra arg d: poe
Variable Length parameters of keywords and non-keywords can be used in the same function, as long as the keyword dictionary is the last parameter and non-key tuples appear before it.
Call an object function with Variable Length Parameters
Some examples of using it are shown:
>>> def newfoo(arg1, arg2, *nkw, **kw):'display regular args and all variable args'print 'arg1 is :', arg1print 'arg2 is :', arg2for eachNKW in nkw:print 'additional non-keyword arg:', eachNKWfor eachKW in kw.keys():print "additional keyword arg '%s': %s"%\(eachKW, kw[eachKW])>>> newfoo('wolf',3,'projects',freud=90,gamble=96)arg1 is : wolfarg2 is : 3additional non-keyword arg: projectsadditional keyword arg 'gamble': 96additional keyword arg 'freud': 90>>> newfoo(10,20,30,40,foo=50,bar=60)arg1 is : 10arg2 is : 20additional non-keyword arg: 30additional non-keyword arg: 40additional keyword arg 'foo': 50additional keyword arg 'bar': 60>>> newfoo(2,4,*(6,8),**{'foo':10,'bar':12 })arg1 is : 2arg2 is : 4additional non-keyword arg: 6additional non-keyword arg: 8additional keyword arg 'foo': 10additional keyword arg 'bar': 12>>> aTuple = (6,7,8)>>> aDict = {'z': 9}>>> newfoo(1,2,3,x=4,y=5, *aTuple, **aDict)arg1 is : 1arg2 is : 2additional non-keyword arg: 3additional non-keyword arg: 6additional non-keyword arg: 7additional non-keyword arg: 8additional keyword arg 'y': 5additional keyword arg 'x': 4additional keyword arg 'z': 9