Python path -10-function

Source: Internet
Author: User
Tags define local variable scope

10.1 function definition and syntax

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

Features: 1. Reduce duplicate code 2. Make the program Extensible 3. Making programs easier to maintain

Syntax Definitions:

Def sayhi (): #函数名

Print ("Hello, I ' m nobody!")

Sayhi () #调用函数

Example 1:

#! Author:lanhan
#定义函数
def func1 ():
"' testing1 '
Print (' in the Func1 ')
return 0

#定义过程 (no function with return value)
def Func2 ():
"' testingn2 '
Print (' in the Func2 ')
#函数调用
X=FUNC1 ()
Y=FUNC2 ()
Print (' from Func1 return is%s ' %x)
Print (' from Func2 return is%s ' %y)

Example 2:

#! Author:lanhan
ImportTime
defLogger ():
Time_format ='%y-%m-%d%x '
    Time_current = Time.strftime (Time_format)
Print (Time.strftime (Time_format))
withOpen' A.txt ',' A + ') asF:
F.write ('%s End action\ n'%time_current)
defTest1 ():
Print' in the Test1 ')
Logger ()
defTest2 ():
Print' in the Test2 ')
Logger ()
defTest2 ():
Print' in the Test2 ')
Logger ()
defTest3 ():
Print' in the Test3 ')
Logger ()
Test1 ()
Test2 ()
Test3 ()

10.2 return value

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

Note: 1. The function will stop executing and return the result as soon as it encounters a return statement, so it can also be understood that the return statement represents the end of the function.

    1. If return is not specified in the function , the return value of this function is None
    2. can return any value of the collection, dictionary, tuple

Example 1:

#! Author:lanhan
def test1 ():
Print (' in the Test1 ')

def test2 ():
Print (' in the Test2 ')
return 0
def test3 ():
Print (' in the Test3 ')
return 1,' Hello ', [' Alex ',' Lanhan '],{' name ':' Lanhan ' }
X=test1 ()
Y=test2 ()
Z=test3 ()
Print (x)
Print (y)
Print (z)

10.3 Parameters

10.3.1-shaped participation arguments

Parameter: The variable allocates the memory unit only when it is called, and immediately releases the allocated memory unit 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 amount of the actual argument, they must have a definite value when making a function call 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

10.3.2 positional parameters and keyword parameters

positional parameters : To pass parameters to the function in order

Keyword parameter: You do not want to use the key parameter in order, just specify the parameter name

Example 1:

#! Author:lanhan
def Test (x, y):
Print (x)
Print (y)
Test #位置参数调用 (corresponds to the parameter one by one, the real parameters need to correspond to the shape parameter, no more or less)
Test (Y=2,x=1) #关键字调用 (independent of formal parameter order)
#位置参数和关键字参数混合使用, pass the value according to the position parameter
#test (x=2,3) #错误 (Key parameters must be write in positional parameters after , the first parameter is the positional parameter the second parameter cannot be the first parameter value)
Test (3,y=2) #正确
#test (3,x=2) #错误

10.3.3 Default Parameters

Features: 1. When calling a function, the default parameter must not be passed

2. If the default parameter value is not passed, the default is the default value. Returns the newly passed value if the default parameter value is passed

Example 1:

#! Author:lanhan
def Test (x,y=2):
Print (x)
Print (y)
Test (1,3) #默认参数赋新值, returns the latest value
Test (1) #默认参数没有赋值, the default parameter value is returned

10.3.4 Non-fixed parameter (parameter group)

Unsure how many arguments are passed to the argument, and the parameter uses a non-fixed argument

Example 1:

#! Author:lanhan
def Test (*args):
Print (args)
Test (1,2,3,4,5,5)
Test (*[1,2,3,4,5,5]) #*args=*[1,2,3,4,5,5]

Example 2:

#*args: Accept n Positional parameters, convert narimoto Group form
def Test (*args):
Print (args)
Test (1,2,3,4,5,5)
Test (*[1,2,3,4,5,5]) #*args=*[1,2,3,4,5,5]
Example 3:
#**kwargs: The way to convert n keyword arguments into a dictionary
def test2 (**kwargs):
Print (Kwargs)
Print (kwargs[' name '])
Print (kwargs[' age ')
Print (kwargs[' sex ')
Test2 (name=' Lanhan ', age=8,sex=' F ')
Test2 (**{' name ':' Lanhan ',' age ': 8,' sex ':' man '}) # Dictionary reference

Example 4:

def test3 (Name,**kwargs):
Print (name)
Print (Kwargs)
Test3 (' Lanhan ', age=18,sex=' m ') #与位置参数, keyword parameter combination
Example 5:
def test4 (Name,age=18,**kwargs):
Print (name)
Print (age)
Print (Kwargs)
Test4 (' Lanhan ', 12,sex=' m ', hobby=' Tesla ') #与默认参数结合

10.3.5 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 in sub-programs that define local variables; global variables work elsewhere

Note: 1. To force changes to global variables within a subroutine, you need the global declaration

2. Global variables are dictionaries, collections, and lists that can be changed within a subroutine of a local variable

Example 1:

#! Author:lanhan
School = "Oldboy edu."
def change_name (name):
Global School #声明局部更改全局变量
School = "Mage Linux"
Print ("Before Change", name)
Name = "Lanhan" #这个函数就是这个变量的作用域
age = 23
Print ("after Change", Name,school)
Name = ' Lanhan '
Change_name (name)
Print ("global variable", name) #
Print ("School:", school)

10.4 Recursion

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

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.

Example 1:

#! Author:lanhan
def Calc (n):
Print (n)
return Calc (n+1)
Calc (0)

Example 2:

def Calc (n):
Print (n)
if int (N/2) >0:
return calc (int (N/2))
Print ("--", N)
Calc (10)

10.5 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.

Example 1:

#! Author:lanhan
def Add (a,b,f):
return F (a) +f (b)
res = Add (3,-6,abs)
Print (RES)

10.6 built-in functions

Python path -10-function

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.