Python basic 13 functions and functional programming

Source: Internet
Author: User

Main content
    1. Basic syntax and characteristics of functions
    2. parameter and local variable
    3. return value 4. recursion
    4. Name function 6. Introduction to Functional programming
    5. Order function 8. Built-in functions
function basic syntax and feature definition

Mathematical function definition: Generally, in a change process, if there are two variables x and Y, and for each determined value of X, Y has a unique value corresponding to it, then we call X as the argument, y is called the dependent variable, Y is the function of X. The range of values of the argument x is called the definition field of the function.

But the concept of "function" in programming, which is the same function as the function in mathematics, is a programming method of logical structure and process.

Advantages of the function
    • Reduce duplicate code
    • To make the program extensible
    • Make programs easier to maintain
Functions and procedures
    • Defining functions
def fun1(): #函数名称"The function decription" print("in the func1") return 0 #返回值
    • Defining the process
def fun2():"The progress decription"print("in the func2")
    • Functions and procedures are functions that do not return a value but in Python, the procedure implicitly returns none by default, so in Python that is, the procedure can also be counted as a function.
def fun1():    "The function decription" print("in the func1") return 0def fun2(): "The progress decription" print("in the func2")x=fun1()y=fun2()print("from func1 return is %s" %x)print("from func2 return is %s" %y)

The result is:

in the func1in the func2from func1 return is 0from func2 return is None
return value

To get the result of a function, you can return the result in the return language.

    1. The function will stop and return the result whenever it encounters a return language, so it can also be solved as a return that represents the end of the function, and if return is not specified in the function, the return value of this function is none.

    2. Accept return value

      Assign variables, for example:

def test():    print(‘in the test‘) return 0x=test()
    1. What variable values are returned

The return number is not fixed, and the return type is not fixed. For example:

DefTest1(): Print (' In the Test1 ')DefTest2 (): print ( ' in the Test2 ') return Span class= "Hljs-number" >0def  Test3 (): print ( ' in the Test3 ')  return 1, ' hello ', [ ' Alex ',  ' Wupeiqi '],{ ' name ':  ' Alex '}return Test2x=test1 () y=test2 () Z=test3 () U=test4 () print (x) print (y) print (z) print (u)  

The result is:

in the test1in the test2in the test3in the test4None0(1, ‘hello‘, [‘alex‘, ‘wupeiqi‘], {‘name‘: ‘alex‘})<function test2 at 0x102439488>
    • Number of return values = 0: Return None no return
    • Number of return values = 1: Returns a value of object return, and Python's basic data types are objects.
    • Number of return values >1: Returns a tuple, return multiple values.
    • Returns the function returned: return TEST2 returns the memory address of the test2.
    1. Why should I have a return value?

The result that you want the entire function to perform. The execution results may be related to the operation. For example, log in and return true to do other things next. If False, the operation is not given.

function parameter parameters and actual parameter definitions
    • Formal parameters

Formal parameters, which are not actually present, are virtual variables. When defining functions and function bodies, use formal parameters to receive arguments (the number of parameters and the type should correspond to the argument one by one) when the function is called.
Variables allocate memory units only when they are tuned

    • Actual parameters

The actual arguments, the arguments that are passed to the function when the function is called, can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when the function is called, they must have a definite value to pass these values to the parameter. Therefore, the parameter should be determined by the method of assignment, input and so on beforehand.

    • Difference

The parameters are virtual and do not occupy memory space. Shape parametric the memory unit is allocated only when called, and the allocated memory unit is freed immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. After the function call finishes returning the keynote function, you can no longer make the parameter variable.

An argument is a variable that consumes memory space, data is routed one-way, arguments are passed to formal parameters, and parameters are not passed to arguments.

def calc(x,y): #x,y为形参 res = x**y return resc = calc(a,b) #a,b为实参print(c)
def test(x,y): #x,y为形参 print(x) print(y)x=1 #x为实参y=2 #y为实参test(x=x,y=y) #等号左边x,y为形参,等号右边x,y为实参,引用不分顺序,按关键字引用。
Default parameters

When defining a function, you can also have default parameters. The function's default parameter is to simplify the call, you just need to pass in the necessary parameters. However, when needed, additional parameters can be passed in to override the default parameter values.

#定义一个计算 x 的N次方的函数,默认是2次方def test6(x,n=2): s=1 while n>0: n=n-1 s=s*x print(s) return stest6(2)

The default parameters can only be defined after the required parameters.

Variable parameters

If you want a function to accept any of the arguments, we can define a variable parameter:

def fn(*args):    print args

The variable parameter has a * number in front of the name, we can pass 0, one or more parameters to the variable parameter: The Python interpreter will assemble the incoming set of parameters into a tuple to pass to the variable parameter, therefore, within the function, directly the variable args as a tuple.

The purpose of defining mutable parameters is also to simplify the invocation. Suppose we want to calculate an arbitrary number of averages, we can define a variable parameter:

def average(*args):    ...

In this way, you can write this at the time of the call:

>>> average()0>>> average(1, 2)1.5>>> average(1, 2, 2, 3, 4)2.4
Positional parameters and keywords

Positional parameter invocation: The actual participating formal parameter position one by one corresponds; Key parameter invocation: position does not need to be fixed.

Normally, the arguments to the function are ordered in order, and if they are not in order, they can be called with the parameter name, but the key parameter must be placed after the position parameter.

def test5(u,v,w):    print(u)    print(v)    print(w)test5(3,w=2,v=6)
Function call

Python has built in a lot of useful functions that we can call directly.

To invoke a function, you need to know the name and parameters of the function, such as an absolute function abs, which receives a parameter.

Call the ABS function:

abs(-21)21

When calling a function, if the number of arguments passed in is incorrect, the TypeError error is reported, and Python will explicitly tell you that ABS () has only 1 parameters, but gives two:

abs(21,8)Traceback (most recent call last): File "/Users/cathy/PycharmProjects/p51cto/day3/func_test3.py", line 67, in <module> abs(21,8)TypeError: abs() takes exactly one argument (2 given)

If the number of arguments passed in is correct, but the parameter type cannot be accepted by the function, the TypeError error is reported, and an error message is given: STR is the wrong parameter type:

abs(‘a‘)Traceback (most recent call last):  File "/Users/cathy/PycharmProjects/p51cto/day3/func_test3.py", line 69, in <module> abs(‘a‘)TypeError: bad operand type for abs(): ‘str‘
Recursive functions

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

For example, let's calculate factorial n! = 1 * 2 * 3 * ... * n, denoted by the function fact (n):

def fact(n):    if n==1: return 1 return n * fact(n - 1)

The advantage of recursive functions is that they are simple in definition and clear in logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.

Nested functions

Python allows the body of a function to contain a complete definition of another function when it is defined.

"test1"def changeout(): name = "test2" def changeinner(): name = "test3" print("changeinner赋值打印", name) changeinner() # 调用内层函数 print("外层调用内层打印", name)changeout()print("调用外层打印", name)

An intrinsic function can access the scope of its outer function, but an external function cannot access the scope of the intrinsic function.

def change1 (name):

anonymous functions

An anonymous function is one that does not require an explicit function to be specified

#这段代码 def Calc (n): Return n**n print (Calc (10))

#换成匿名函数 calc = lambda n:n**n print (Calc (10))

Function-Type programming

In other words, "functional programming" is a "programming paradigm" (programming paradigm), which is how to write a program's methodology.

The main idea is to write the operation process as much as possible into a series of nested function calls.

Reference page

Http://www.cnblogs.com/alex3714/articles/5740985.html

http://www.imooc.com/code/3516

http://blog.csdn.net/suncherrydream/article/details/51682560

Http://www.jb51.net/article/68314.htm

Python basic 13 functions and functional programming

Related Article

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.