〖python〗--function

Source: Internet
Author: User
Tags function definition




function


function is interpreted as ubroutine (child process or subprocess) in the computer

 function definition : A function refers to the collection of a set of statements by a name (function name) to encapsulate, to execute this function, just call their function name to

 Syntax Definitions:

With no parameters:

def # Name of function Print ("Hello, world! "  # Call function          

With parameters:

        

#下面这段代码 A, b = 5,8 c = a**b print (c)  #改成用函数写 def calc (x, y):    res = x**y    Retu RN res #返回函数执行结果 c = Calc (b) # result assigned to c variable print (c)

    Function Properties :

1 Reduce Duplicate code

2 Improving Code Extensibility

3 Make the program easy to maintain

  Parameters

Required Parameters

The function must be passed in the order defined by the parameter, and must be called in order.

      

def f (name,age):    print (' I am%s,i am%d '% (Name,age)) F (' shengxin ', +) F (' Alvin ', 16)

Keyword parameters

The so-called keyword parameter, similar to the dictionary key-value pairs, is called by the keyword function, which is equivalent to the key to find the value.

      

def f (name,age):     print (' I am%s,i am%d '% (name,age)) # f (+, ' Alvin ') #报错 F (age=16,name= ' Alvin ')

Default parameters

On the basis of the keyword parameters, some parameters to the default value, do not modify the words, display the default value, do not modify the call, will automatically display

def print_info (name,age,sex= ' male '):  #默认参数放在最后    print (' name:%s '%name)  print (' age:%s '%age)   p Rint (' sex:%s '%sex)    return print_info (' shengxin ')    #sex不给值, showing the default value Print_info (' Hammer ', ' max ', ' female ')  #修改s Ex value, showing the modified value    

Indefinite length parameter

In case the user input parameter is indeterminate, the indefinite length parameter is used, and the classification is as follows:

*kwargs

Multiple passed-in parameters are saved in the form of tuples

        

def stu_register (Name,age,*args): # *args will turn multiple incoming parameters into a tuple form    print (Name,age,args) stu_register ("Shengxin", 22 #输出 #ShengXin () #后面这个 () is args, just because there is no value, so it is empty stu_register ("Jack", "+", "CN", "Python") #输出 # Jac K (' CN ', ' Python ')

**kwargs

Multiple incoming parameters are saved in a dictionary

      

def stu_register (Name,age,*args,**kwargs): # *kwargs will turn multiple incoming parameters into a dict form   print (Name,age,args,kwargs) stu_r Egister ("Shengxin") #输出 #Alex () {} #后面这个 {} is Kwargs, just because no value is passed, so it is empty stu_register ("Jack", "+", "CN", "Python" , sex= "Male", province= "Shandong") #输出 # Jack (' CN ', ' Python ') {' Province ': ' Shandong ', ' sex ': ' Male '}

  Local variables

A function with the same name is redefined in the function, the function value is valid inside the function, the scope is a function, the variable defined is a local variable

    

Name = "Shengxin" #全局变量 def change_name (name):   print ("Before change:", name)   name = "changed name" 
    #局部变量  print ("After Change", name) change_name (name)  print ("Look outside name changed?", name)    

return value

Return

In the function, return ends the execution of this layer and returns the result

The default return value for a function is: none

  Recursive

Calling the function itself in a function

    

Def calc (n):   print (n)    if int (N/2) ==0:       return n   return calc (int (N/2)) Calc (10)

Characteristics:

Must have a definite end condition

The computational scale should be reduced each time you enter the next level of recursion

Recursive functions are inefficient, and excessive recursion can result in stack overflow

  anonymous functions

Using lambda in Python to create anonymous functions

Format:

Lambda arg1,arg2 ... : <expression>

    

    
#算一个数的平方
Def calc (n): return n**n print (calc) #换成匿名函数 calc = lambda n:n**n print (Calc (10))

Role:

Anonymous functions are mostly used in conjunction with other functions.

      

res = map (lambda x:x**2,[1,5,7,4,8]) for I in res:  print (i)    

  Function-Type programming

  Higher order functions

Function names can be entered as parameters

Function name can be returned as a value

    

def add (x,y,f):   return F (x) + f (y)  res = Add (3,-6,abs) print (res)

  Built-in functions

Python built-in functions

  

Scope

  The scope in Python is divided into 4 scenarios:

  • l:local, local scope, which is the variable defined in the function;
  • E:enclosing, the local scope of the nested parent function, which is the local scope of the ancestor function that contains the function, but not the global;
  • G:globa, a global variable, is a variable defined at the module level;
  • B:built-in, the variables inside the system fixed module, such as int, ByteArray, etc. The order of precedence for a search variable is: scope local > Outer scope > Global >python Built-in scope in the current module, that is, LEGB.
    x = Int (2.9)  #  int built-in  = 0  #  globaldef  Outer ():    = 1  #  enclosing    def  Inner ():        = 2  #   Local        Print (o_count)     # print (i_count) not found     Inner () outer ()  #  print (o_count) #找不到

      

〖python〗--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.