Python3 function knowledge includes definition, call, parameters, variables and other detailed examples

A function is a well-organized, reusable piece of code used to implement a single, or related, function.

Functions can increase the modularity of the application and the reuse of code. Python provides many built-in functions, such as print(). But you can also create a function yourself, which is called a user-defined function.

Python3 function knowledge includes definition, call, parameters, variables and other detailed examples

1. The definition of the function:

You can define a function that you want to use. Here are the simple rules:

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

Any incoming parameters and arguments must be placed in the middle of parentheses. Parentheses can be used to define parameters.

The first line of the function can optionally use a docstring—used to hold a function description.

The contents of the function start with a colon and are indented.

The pass keyword means nothing

Exit(num) forced exit (num: is a number, shown as an exit code)

Return [expression] An end function that optionally returns a value to the caller. A return without an expression is equivalent to returning None.

grammar

Def functionname( parameters ): function_suite return [expression]

By default, parameter values ​​and parameter names are matched in the order defined in the function declaration.

Example 1:

Def add(x, y):print("x = {0}".format(x))print("x = {0}".format(x))print(" x + y = {0}". Format(x+y))return x+y

Example 2:

#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2018/4/14 20:31# @Author : Feng Xiaoqing# @File : demo1.py# @Function: -----------def f(x,l=[]): for i in range(x): l.append(i*i) print(l)# f(2) = f( 2, l=[])f(2)# Result: [0, 1]f(3,[3,2,1])# Result: [3, 2, 1, 0, 1, 4]f(x =3, l=[])# Results: [0, 1, 4]

operation result:

[0, 1][3, 2, 1, 0, 1, 4][0, 1, 4]

2 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 from another function call, or from the Python prompt.

The following example calls the add() function:

#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2018/4/15 21:01# @Author : Feng Xiaoqing# @File : demo2.py# @Function: -----------# Custom Addition Function add()def add(x,y): print("{0} + {1} = {2}".format(x,y,x +y)) return print("finished") # This statement will not be executed after return # Call the function and calculate the 2+3 add(2,3)

operation result:

2 + 3 = 5

3 function parameters

Formal parameters and actual parameters

When defining a function, the name of the variable in parentheses after the name of the function is called a formal parameter, or "formal parameter"

When the function is called, after the function name, the name of the variable in parentheses is called the actual parameter, or "actual parameter"

Def fun(x,y): //param print(x + y) fun(1,2) //actual 3 fun('a','b') ab

Function default parameters:

Default parameters (default parameters)

Def fun(x,y=100) print x,y#call:fun(1,2)fun(1)

definition:

#!/usr/bin/env python# -*- coding: utf-8 -*-def fun(x=2,y=3): print x+y

transfer:

Fun()#Results:5fun(23)#Results26fun(11,22)# Results:33

We often see other people's code, def (* args, ** kwargs) such manifestations:

*args means: tuple (1,) **kwargs means dict {"k": "v"}fun(*args, **keargs)fun(1, 2, 3, 4, 5, a =10, b=40)

The return value of the function

Function return value:

A function returns a specified value after it is called

Default return None after function call

Return return value

The return value can be any type

After the return execution, the function terminates

The difference between return and print

#!/usr/bin/env python# -*- coding:utf-8 -*-def fun(): print 'hello world' return 'ok' print 123fun()#results hello world123None

5. Function variables

Local variables and global variables:

Any variable in Python has a specific scope

The variables defined in the function can only be used inside the function. Variables that can only be used in specific parts of the program are called local variables.

Variables defined at the top of a file can be called by any function in the file. These can be called global variables for the entire program.

Def fun(): x=100 print xfun()x = 100def fun(): global x // declare x +=1 print xfun()print x

External variables were changed (x changed from 100 to 101):

x = 100def fun(): global x x += 1 print (x)fun()print (x)# result 101101

Internal variables are also available externally:

#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2018/4/15 21:33# @Author : Feng Xiaoqing# @File : demo2.py# @Function: -----------x = 100def fun(): global xx +=1 global yy = 1 print(x)fun()print(x)print(y)# Result: 1011011

The variables in the statistics program return a dictionary

#!/usr/bin/env python# -*- coding:utf-8 -*-x = 100def fun(): x = 1 y = 1 print(locals())fun()print (locals())

result:

{'y': 1, 'x': 1}{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x02FF6390>, '__spec__' : None, '__annotations__': {}, '__builtins__': , '__file__': 'D:/PycharmProjects/PythonLive/untitled/day07/demo2.py', '__cached__': None, 'x': 100, 'fun': }

6. Anonymous function

As the name suggests is a function with no name, then why should we set up an anonymous function, what role does he have? A lambda function is a minimal function that quickly defines a single row and can be used wherever a function is needed

Python uses lambda to create anonymous functions.

A lambda is just an expression. The function body is much simpler than def.

The body of the lambda is an expression, not a block of code. 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 be able to write only one line, it is not the same as the inline function of C or C++. The purpose of the latter is to call the small function without occupying the stack memory and thus increase the operating efficiency.

grammar

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

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

For example:

Find the product of two numbers:

Conventional writing:

Def fun(x,y) return x*y

The lambda version is written:

r = lambda x,y:x*y

7. Higher-order functions

(1) map(f, list)

Returns a list of the values ​​of each element evaluated by f

The map() function takes two arguments, one is a function and one is a sequence. The map applies the passed function to each element of the sequence in turn and returns the result as a new list.

Example: Calculate the square of the value in the list

#!/usr/bin/env python# -*- coding:utf-8 -*-def f(x): return x*xfor i in map(f,[1,2,3,4,5,6, 7]): print(i)

result:

14916253649

(2) reduce (f, list) function (sum of the number in the list)

Reduce applies a function to a sequence [x1, x2, x3...]. This function must receive two arguments. Reduce performs the cumulative calculation on the next element of the sequence. The effect is:

Example: Calculate the sum of all the numbers in the list

#!/usr/bin/env python# -*- coding:utf-8 -*-from functools import reduce #import reduce function def f(x,y): return x+yprint(reduce(f,[1,2 ,3,4,5,6,7,8,9,10]))print(reduce(f,range(1,101)))#Results:555050

(3) filter() function (filtering)

The filter function receives a function f and a list. The function of function f is to judge each element and return True or False. filter() automatically filters out elements that do not meet the conditions according to the judgment result, and returns a list of elements that meet the requirements.

Filter(lamdba x: x%2 ==1, [1, 2, 3, 4, 5])

Example: Calculate the number less than 7 in the list

#!/usr/bin/env python# -*- coding:utf-8 -*-for i in filter(lambda x:x<7, [1, 2, 3, 4, 5,40,8]): Print(i)# result: 12345

(4) sorted () function (sort)

Sorted(...) sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

# sorted(iterable, key, reverse)# iterable An iterable object # key What to sort # reverse bool type, if true is in reverse order, the default is false # The return value is a list

For example:

#!/usr/bin/env python# -*- coding: utf-8 -*-# @Time : 2018/4/15 22:47# @Author : Feng Xiaoqing# @File : demo3.py# @Function: -----------m = dict(a=1, c=10, b=20, d=15)print(sorted(m.items(), key = lambda d:d[1] ,reverse = True)) #The result is in descending order of value:[('b', 20), ('d', 15), ('c', 10), ('a', 1)]

Stainless Steel Hexagonal Bar

Stainless Steel Hexagonal Bar,420 Stainless Steel Hexagonal Bar,Stainless Steel Bar Metal Rod,Stainless Steel Bar Top

ShenZhen Haofa Metal Precision Parts Technology Co., Ltd. , https://www.haofametal.com

Posted on