This article mainly introduces the usage of functions in Python, including the creation, definition, and parameters of functions, for more information about the usage of Python functions, see the following example. Share it with you for your reference. The specific analysis is as follows:
Generally, a Python function is written by a new statement, that is, def, def is an executable statement-the function does not exist until Python runs def.
A function is passed through a value assignment, and a parameter is passed to the function through a value assignment.
The def statement creates a function object and assigns it to a variable name. The general format of the def statement is as follows:
def
(arg1,arg2,arg3,……,argN):
The def statement is executed in real time. When it is run, it creates and assigns a new function object to a variable name. All Python statements are executed in real time, there is no process like independent Compilation Time
Because it is a statement, def can appear where any statement can appear-or even nested in other statements:
if test: def fun(): ...else: def func(): ......func()
You can assign a function to a different variable name and call it using the new variable name:
othername=func()othername()
Create a function
The built-in callable function can be used to determine whether the function is callable:
>>> import math>>> x=1>>> y=math.sqrt>>> callable(x)False>>> callable(y)True
Use del statements to define functions:
>>> def hello(name): return 'Hello, '+name+'!'>>> print hello('world')Hello, world!>>> print hello('Gumby')Hello, Gumby!
Compile a function of the fibnacci series:
>>> def fibs(num): result=[0,1] for i in range(num-2): result.append(result[-2]+result[-1]) return result>>> fibs(10)[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]>>> fibs(15)[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
Assigning values to parameters in a function does not change the values of any external variables:
>>> def try_to_change(n): n='Mr.Gumby'>>> name='Mrs.Entity'>>> try_to_change(name)>>> name'Mrs.Entity'
Because strings (as well as tuples and numbers) cannot be changed, the parameters will not change. However, what will happen when a variable data structure such as a list is used as a parameter:
>>> name='Mrs.Entity'>>> try_to_change(name)>>> name'Mrs.Entity'>>> def change(n): n[0]='Mr.Gumby'>>> name=['Mrs.Entity','Mrs.Thing']>>> change(name)>>> name['Mr.Gumby', 'Mrs.Thing']
The parameter has changed, which is an important difference from the previous example.
Do not use the following function again:
>>> Name = ['Mrs. entity ', 'Mrs. thing ']> n = name # Again, simulate parameter passing behavior> n [0] = 'Mr. gumby' # change the list> name ['Mr. gumby', 'Mrs. thing ']
When two variables reference a list at the same time, they do reference a list at the same time. To avoid this situation, you can copy a copy of the list. When slicing is performed in the sequence, the returned slice is always a copy, so if you copy the slice of the entire list, you will get a copy:
>>> names=['Mrs.Entity','Mrs.Thing']>>> n=names[:]>>> n is namesFalse>>> n==namesTrue
Changing n does not affect names:
>>> n[0]='Mr.Gumby'>>> n['Mr.Gumby', 'Mrs.Thing']>>> names['Mrs.Entity', 'Mrs.Thing']>>> change(names[:])>>> names['Mrs.Entity', 'Mrs.Thing']
Keyword parameters and default values
Parameters can be ordered by providing the parameter name (but the parameter name and value must correspond ):
>>> def hello(greeting, name): print '%s,%s!'%(greeting, name)>>> hello(greeting='hello',name='world!')hello,world!!
The most powerful keyword parameter is that the default value can be provided to the parameter:
>>> def hello_1(greeting='hello',name='world!'): print '%s,%s!'%(greeting,name)>>> hello_1()hello,world!!>>> hello_1('Greetings')Greetings,world!!>>> hello_1('Greeting','universe')Greeting,universe!
If you want greeting to use the default value:
>>> hello_1(name='Gumby')hello,Gumby!
It is not difficult to implement the function by providing any number of parameters:
>>> def print_params(*params): print params>>> print_params('Testing')('Testing',)>>> print_params(1,2,3)(1, 2, 3)
Mixed common parameters:
>>> def print_params_2(title,*params): print title print params>>> print_params_2('params:',1,2,3)params:(1, 2, 3)>>> print_params_2('Nothing:')Nothing:()
The asterisk indicates "collecting other location parameters". If no element is provided for collection, params is an empty tuples.
However, keyword parameters cannot be processed:
>>> print_params_2('Hmm...',something=42)Traceback (most recent call last): File "
", line 1, in
print_params_2('Hmm...',something=42)TypeError: print_params_2() got an unexpected keyword argument 'something'
Try "**":
>>> Def print_params (** params): print params >>> print_params (x = 1, y = 2, z = 3) {'y': 2, 'X': 1, 'z': 3 }>>> def parames (x, y, z = 3, * pospar, ** keypar): print x, y, z print pospar print keypar >>> parames (1, 2, 3, 5, 6, 7, foo = 1, bar = 2) 1 2 3 (5, 6, 7) {'foo ': 1, 'bar': 2 }>>> parames (1, 2) 1 2 3 () {}>>> def print_params_3 (** params ): print params >>> print_params_3 (x = 1, y = 2, z = 3) {'y': 2, 'x': 1, 'z ': 3 }>>> # The returned value is a dictionary instead of a tuples >>## composite '#' and '##' >>> def print_params_4 (x, y, z = 3, * pospar, ** keypar): print x, y, z print pospar print keypar >>> print_params_4 (1, 2, 3, 5, 6, 7, foo = 1, bar = 2) 1 2 3 (5, 6, 7) {'foo': 1, 'bar': 2 }>>> print_params_4 (1, 2) 1 2 3 (){}
I believe this article has some reference value for everyone's learning about Python programming.