The path to learning in Python--day3

Source: Internet
Author: User
Tags define local variable scope

The content of this section

1. Basic function syntax and features

2. Parameters and Local variables

3. Return value

4. Recursion

5. Anonymous functions

6. Introduction to Functional programming

7. Higher-order functions

8. Built-in functions

1. What is the basic syntax and function of the function?

function is derived from mathematics, but the concept of "function" in programming is very different from the function in mathematics, the specific difference, we will say later, the function of programming in English also has a lot of different names. In basic it is called subroutine (sub-process or subroutine), in Pascal is called procedure (process) and function, in C only function, in Java is called method.

Definition: A function that encapsulates a set of statements by a name (function name), and to execute the function, simply call the name of its functions

Characteristics:

    1. Reduce duplicate code
    2. To make the program extensible
    3. Make programs easier to maintain
Syntax definitions
1234 defsayhi():#函数名    print("Hello, I‘m nobody!")sayhi() #调用函数

can take parameters

12345678910111213 #下面这段代码a,b =5,8=a**bprint(c)#改成用函数写defcalc(x,y):    res =x**y    returnres #返回函数执行结果=calc(a,b) #结果赋值给c变量print(c)

2. Function parameters and Local variables

Parametric the memory unit is allocated only when called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. Function call ends when you return to the keynote function, you can no longer use the shape parametric

Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when a function call is made, they must have a definite value in order to pass these values to the parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value

Default parameters

Look at the code below

12345678910 defstu_register(name,age,country,course):    print("----注册学生信息------")    print("姓名:",name)    print("age:",age)    print("国籍:",country)    print("课程:",course)stu_register("王山炮",22,"CN","python_devops")stu_register("张叫春",21,"CN","linux")stu_register("刘老根",25,"CN","linux")

Found country This parameter is basically "CN", just like we registered users on the site, such as the nationality of this information, you do not fill in, the default will be China, which is implemented by default parameters, the country into the default parameters is very simple

1 defstu_register(name,age,course,country="CN"):

Thus, this parameter is not specified at the time of invocation, and the default is CN, specified by the value you specify.

In addition, you may have noticed that after turning the country into the default parameter, I moved the position to the last side, why?

Key parameters

Under normal circumstances, to pass parameters to the function in order, do not want to order the key parameters can be used, just specify the parameter name, but remember a requirement is that the key parameters must be placed after the position parameter.

1 stu_register(age=22,name=‘alex‘,course="python",)

  

Non-fixed parameters

If your function is not sure how many parameters the user wants to pass in the definition, you can use the non-fixed parameter

12345678910 defstu_register(name,age,*args): # *args 会把多传入的参数变成一个元组形式    print(name,age,args)stu_register("Alex",22)#输出#Alex 22 () #后面这个()就是args,只是因为没传值,所以为空stu_register("Jack",32,"CN","Python")#输出# Jack 32 (‘CN‘, ‘Python‘)

can also have a **kwargs

12345678910 defstu_register(name,age,*args,**kwargs): # *kwargs 会把多传入的参数变成一个dict形式    print(name,age,args,kwargs)stu_register("Alex",22)#输出#Alex 22 () {}#后面这个{}就是kwargs,只是因为没传值,所以为空stu_register("Jack",32,"CN","Python",sex="Male",province="ShanDong")#输出# Jack 32 (‘CN‘, ‘Python‘) {‘province‘: ‘ShanDong‘, ‘sex‘: ‘Male‘}

Local variables
1234567891011 name ="Alex Li"defchange_name(name):    print("before change:",name)    name ="金角大王,一个有Tesla的男人"    print("after change", name)change_name(name) print("在外面看看name改了么?",name)

Output

123 before change: Alex Liafter change 金角大王,一个有Tesla的男人在外面看看name改了么? Alex Li

Global vs. local variables

A variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable. The global variable scope is the entire program, and the local variable scope is the subroutine that defines the variable. When a global variable has the same name as a local variable: Local variables work within subroutines that define local variables, and global variables work in other places.

3. Return value

To get the result of the function execution, you can return the result using the return statement

Attention:

    1. The function stops executing and returns the result as soon as it encounters a return statement, so can also be understood as a return statement that represents the end of the function
    2. If return is not specified in the function, the return value of this function is None

  

  

4. Recursion

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

12345678910111213 defcalc(n):    print(n)    ifint(n/2==0:        returnn    returncalc(int(n/2))calc(10)输出:10521

Recursive properties:

1. There must be a clear end condition

2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion

3. Recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.

5. Anonymous functions

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

12345678 #这段代码defcalc(n):    returnn**nprint(calc(10))#换成匿名函数calc =lambdan:n**nprint(calc(10))

You may say that it is not convenient to use this thing. Oh, if it is so used, there is no yarn improvement, but the anonymous function is mainly used with other functions, as follows

123 res =map(lambdax:x**2,[1,5,7,4,8])forinres:    print(i)

Output

1
25
49
16
64

6. Introduction to Functional programming

function is a kind of encapsulation supported by Python, we can decompose complex tasks into simple tasks by splitting large pieces of code into functions through a layer of function calls, which can be called process-oriented programming. function is the basic unit of process-oriented program design.

and functional programming (note that more than one "type" word)--functional programming, although it can also be attributed to the process-oriented programming, but the idea is closer to the mathematical calculation.

We first have to understand the concepts of computer (computer) and computational (Compute).

At the level of the computer, the CPU executes the subtraction instruction code, as well as various conditional judgments and jump instructions, so, assembly language is the most close to the computer languages.

And the calculation of the exponential meaning, the more abstract calculation, the farther away from the computer hardware.

corresponding to the programming language, is the lower level of the language, the more close to the computer, low degree of abstraction, implementation of high efficiency, such as C language, the more advanced language, the more close to the computation, high degree of abstraction, inefficient execution, such as Lisp language.

Functional programming is a very high degree of abstraction of the programming paradigm, the purely functional programming language functions are not variable, so any function, as long as the input is determined, the output is OK, this pure function we call no side effects. In the case of programming languages that allow the use of variables, because of the variable state inside the function, the same input may get different output, so this function has side effects.

One of the features of functional programming is that it allows the function itself to be passed as a parameter to another function, and also allows a function to be returned!

Python provides partial support for functional programming. Because Python allows the use of variables, Python is not a purely functional programming language.

First, the definition

Simply put, "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. For example, there is now a mathematical expression:

(1 + 2) * 3-4

Traditional procedural programming, which may be written like this:

var a = 1 + 2;

var B = A * 3;

var c = b-4;

Functional programming requires the use of functions, which can be defined as different functions, and then written as follows:

var result = Subtract (multiply (add), 3), 4);

This is functional programming.

Well, that's all I can do ...

7. Higher-order functions

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.

123456 defadd(x,y,f):    return  f(x) + f(y) res =add(3,-6,abs)print(res)

8. Built-In Parameters

The path to learning in Python--day3

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.