Python Basics (v) function

Source: Internet
Author: User

I. Function concept

The term function is derived from mathematics, but the concept of "function" in programming is very different from the function in mathematics, and the function in programming has many different names in English. 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 is a collection of a set of statements by a name (function name) encapsulated, in order to execute this function, just call its function name.

Two. Benefits of using functions

1. Simplify Your code

2. Improve the reusability of code

3. Code can be extended

Three. Definition of functions in Python

The definition function uses the DEF keyword, followed by the function name, and the function name cannot be duplicated

def Sayhi(): # function name

Print ("Hello, World") #函数体

Sayhi () # call Function

Four. Parameters of the function

1. When the function is called, it can pass in parameters, tangible parameters and actual arguments.

Formal parameters: 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.

Arguments: Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when making a function call, they must have a definite value in order to pass these values to the parameter. The parameter variable can no longer be used after the function call finishes returning the keynote function.

Def calc (x, y): #定义一个函数, parameters are X and y,x and y are formal parameters

print (x*y) # output x multiplied by Y value

Calc (5,2) #调用上面定义的函数, 5 and 2 are arguments

Simply put, the parameter is the argument that the function receives, and the argument is the parameter you actually passed in.

2. Four parameter types for functions

positional parameters : According to the location of parameters, such as the Calc function above, x and Y are positional parameters, positional parameters are required to pass,

There are several positional parameters at the time of the call to pass a few, otherwise it will be error, if there are multiple positional parameters, you can not remember which location to pass what to do, you may use the name of the positional parameter to specify the call

For example, the Calc function above can also be called by using Calc (y=1,x=2), which is called the keyword argument.

default parameter : The default parameter is when defining formal parameters, assign a value to the function by default, such as the port of the database, the default is to give it a value, so even if you do not pass this parameter in the call, it is also a value

So, the default parameter is not required, and if you pass the value to the default parameter, it will use the value you passed in. If a default value parameter is used, it must be defined after the position parameter.

def conn_mysql (user,passwd,port=3306): #定义一个连接mysql的方法, although this method is not connected Mysql,port is a default value parameter

Print (User,passwd,port)

Conn_mysql (' root ', ' 123456 ') #没指定默认值

Conn_mysql (' root ', ' 123456 ', port=3307) #指定默认值参数的值

non-fixed parameters : The above two positional parameters and the default parameters are the number of parameters is fixed, if I am a function, the parameters are not fixed, I do not know the future of this function will expand into what kind of, may be more and more parameters, this time if the fixed parameters, then the program is not good extension, At this time, we can use non-fixed parameters, there are two kinds of non-fixed parameters, one is a variable parameter, and one is a keyword parameter.

variable parameters: variable parameters are received with a *, the number of arguments to pass after the number of passes, if the positional parameters, default parameters, variable parameters used together, the variable parameter must be in the position parameter and the default value after the parameter. Variable parameters are also non-mandatory.

def more_arg (name,age,sex= ' nan ', *agrs): #位置参数, default parameter, variable parameter, variable parameter will put the parameters of the subsequent passes to the args tuple

#当然args名字是随便写的, but in general we all write args.

Print (NAME,AGE,AGRS)

More_arg (' Marry ', ' nv ', ' Python ', ' China ') #调用

Keyword parameters : keyword parameter use * * to receive, the following parameters are not fixed, want to write how many write how many, of course, can also be used with the above several, if you want to use the keyword parameter must be in the last side.

With keyword arguments, you must use the keyword argument when calling. Keyword parameters are also non-mandatory.

def kw_arg (Name,**kwargs): #位置参数, keyword arguments, when called to put the passed keyword parameters into the Kwargs dictionary

Print (Name,kwargs)

Kw_arg (' Sriba ', sex= ' man ', age=18) #调用, sex and age are key words to call

Five. return value of function

Each function has a return value, if it is not specified in the function of the return value, after the function is executed in Python, the default will return a none, the function can have more than one return value, if there are multiple return values, the return value will be placed in a tuple, the return is a tuple.

Why should there be a return value, because after this function is finished, its result will need to be used in the later program.

The return value in the function uses return, and the function ends immediately when it encounters a return.

Def calc (x, y): #这个就是定义一个有返回值的函数

c = X*y

Return C,x,y

res = Calc (5,6) #把函数的返回结果赋值给res

Print (RES)

Six. Local variables and global variables

Local variable meaning is in the local effect, out of the scope of the variable, this variable is invalid, such as the above C is a local variable, after this function, there is no C this value.

Global variables mean that the whole program is in effect, in the first definition of the program is the global variables, global variables if you want to modify in the function, you need to add the Global keyword declaration, if it is a list, dictionary and collection, you do not need to add the global keyword, directly can be modified.

name = ' Marry ' #字符串全局变量

names = [] #list全局变量

Print (name)

Print (names)

def test ():

Global name #修改name的值就需要用global关键字

name = ' Lily '

Names.append (name) #修改全局变量names的值

return names

Test () #调用函数

Print (' modified ', name)

Print (' modified names ', names)

Seven. Recursive invocation

Inside a function, other functions can be called, and if a function calls itself internally, the function is a recursive function.

Recursive invocation means that within this function itself calls itself, the meaning of the point loop, write a recursive, as follows:

def test1 ():

num = Int (input (' Please enter a number: '))

If num%2 = = 0: #判断输入的数字是不是偶数

Return Ture #如果是偶数的话, the program exits and returns True

Print (' Not even re-enter ')

return test1 () #如果不是偶数的话继续调用自己, enter a value

Print (Test1 ()) #调用test

Characteristics of recursive invocation:

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.

Python Basics (v) 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.