Graphic Python "Third": python-function

Source: Internet
Author: User
Tags define local generator generator iterable types of functions variable scope

A list of the contents of this section

First, the function introduction1. What is a function

2. Define a function

You can define a function that you want to function, and here are the simple rules:

      • The function code block begins with a def keyword followed by the function identifier name and parentheses ().
      • Any incoming parameters and arguments must be placed in the middle of the parentheses, and the parentheses can be used to define the parameters.
      • The first line of the function statement can optionally use the document string-for storing the function description.
      • The function contents begin with a colon and are indented.
      • return [expression] ends the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.
      •  

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
3. function Syntax:

second, function parameters and local variables

List:

  

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

1. Default Parameters

Look at the code below

12345678910 def stu_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?

2. 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",)

  

3, 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 def stu_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 def stu_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‘}

4. Local Variables
1234567891011 name = "Alex Li" def change_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

5. Global and local variablesA 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; global variables work elsewhere

III. Basic types of functions1. anonymous function

Lambda expression

####################### Common function #######################defining functions (normal way)deffunc (ARG):returnARG + 1    #Execute functionresult = Func (123)    ####################### Lambda ######################    #Defining a function (lambda expression)My_lambda =LambdaArg:arg + 1    #Execute functionresult = MY_LAMBDA (123)
View Code

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

# this piece of code def Calc (n): return n**nprint(calc)  # change to anonymous function lambda n:n** N Print (Calc (10))
View Code

The anonymous function has a limit, that is, there can be only one expression, not write return , the return value is the result of the expression

# !/usr/bin/python3 # Writable Function Description Lambda arg1, arg2:arg1 +#  calls the Sum function print ("" , sum (ten ))print ("", SUM (20, 20))
View Code

Summary

Python's support for anonymous functions is limited, and anonymous functions can be used only in some simple cases.

    • Lambda is just an expression, and the function body is much simpler than def.
    • The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression.
    • The lambda function has its own namespace and cannot access parameters outside its own argument list or in the global namespace.
    • Although the lambda function appears to be only a single line, it is not equivalent to a C or C + + inline function, which is designed to call small functions without consuming stack memory to increase operational efficiency.

2. Recursive function

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

At the end of a recursive call, if optimized, the stack does not grow, so no amount of calls will cause the stack to overflow.

Unfortunately, most programming languages are not optimized for tail recursion, and the Python interpreter is not optimized, so even if the above function is changed to fact(n) tail recursion, it can cause the stack to overflow.

Summary

The advantage of using a recursive function is that the logic is simple and clear, and the disadvantage is that too-deep calls cause a stack overflow.

The language that is optimized for tail recursion can prevent stack overflow by tail recursion. The tail recursion is actually equivalent to the loop, and the programming language without the loop statement can only be looped by the tail recursion.

The Python standard interpreter is not optimized for tail recursion, and there is a stack overflow problem with any recursive function.

3, the decorative deviceSummary

In the object-oriented (OOP) design pattern, the decorator is called the adornment mode. The Deco pattern of OOP needs to be implemented through inheritance and composition, while Python supports decorator directly from the syntax level, in addition to the decorator of OOP. Python's decorator can be implemented using functions or classes.

Decorator can enhance the function of functions, although it is a bit complex to define, but it is very flexible and convenient to use.

4. Built-in functions

  

Note: View detailed bash here

Iv. Advanced Features:1. Generator Generator

In Python, this side loop computes the mechanism, called the generator: generator

Definition: When a function call returns an iterator, the function is called the Generator (generator), and if the function contains the yield syntax, the function becomes the generator

The first method is simple, as long as a list of the generated formula is [] changed () to create a generator:

next()get the next return value of generator by function

Use for loops, because generator is also an iterative object

The second method. If a function definition contains a yield keyword, then the function is no longer a normal function, but a generator:

2. Iteration

Given a list or tuple, we can iterate through for the list or tuple through a loop, which we call an iteration (iteration)

In Python, iterations are for ... in done through, and in many languages such as C or Java, the iteration list is done by subscript

Any iteration object can be used for for loops, including our custom data types, as long as the iteration criteria are met, the loop can be used for

3, iterator iterator

Iterators are a way to access the elements of a collection.

An iterator is an object that remembers where to traverse.

The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back.

Iterators have two basic methods:iter () and next ().

A string, list, or tuple object can be used to create an iterator

forThere are several types of data that can be directly acting on a loop:

A class is a collection of data types, such as,,, list tuple , and dict set str so on;

One is generator to include the generator and yield the generator function with the band.

These objects, which can be directly applied to for the loop, are called iterative objects: Iterable .

You can use to isinstance() determine whether an object is an Iterable object:

Generators are Iterator objects, but,, list dict str Though Iterable they are, they are not Iterator .

Turn list , dict wait, and str Iterable turn into Iterator functions that can be used iter()

Characteristics:

    1. The visitor does not need to care about the structure inside the iterator, but simply continues to fetch the next content through the next () method
    2. A value in the collection cannot be accessed randomly, and can only be accessed from beginning to end
    3. You can't go back halfway through the interview.
    4. Facilitates recycling of large data sets, saving memory
Summary

Any object that can be used for for the loop is a Iterable type;

All objects that can be used for next() functions are Iterator types, which represent a sequence of lazy computations;

Collection data types such as list , dict ,, and str so on are Iterable not Iterator , however, you can iter() get an object from a function Iterator .

The Python for loop is essentially next() a function of calling functions.

Statement:

I am learning the old boy Python Automation network course, combined with the study to make a note, the content of this article more

Alex Teacher Blog: http://www.cnblogs.com/alex3714/articles/5740985.html

Wu Jianzi Teacher Blog: http://www.cnblogs.com/wupeiqi/articles/5453708.html

Thank the old boy education teacher Alex, Wu Jianzi teacher, this article from two teachers to combine the article to organize

Thanks to Muggle programming Marquis

Http://www.runoob.com/python3/python3-basic-syntax.html

Https://python.xiaoleilu.com/100/101.html

http://www.ituring.com.cn/book/1863

Https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/ 0014318435599930270c0381a3b44db991cd6d858064ac0000

Graphic Python "Third": python-function

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.