Summary python function relatively wide use

1, the definition of the function

Format: DEF <function name> (<parameter (0 or more)>):
   <function body>
    return <Return value>

2, the function of the optional parameters

When the function definition, optional parameters may be used. When using the optional parameter should be placed behind the non-optional parameters, and then call this function when the optional parameters can not give it a value
such as:

def fact(n,m = 1):
    s = 1
    for i in range(1,n+1):
        s *= i
    return s//m
print(fact(10))
print(fact(10,10))

3, the function of the variable parameter

Refers to the total number of functions defined time uncertain parameters: variable parameters

def fact(n,*b):
    s = 1
    for i in range(1,n + 1):
        s *= i
    for item in b:
        s *= item
    return s

print(fact(10,3))
print(fact(10,3,4,5,6))

This is time and b is a combination of a data type

4, transmission parameters

When function calls, passing parameters can be passed in accordance with the location or the name of fashion

def fact(n,m=1):
    s = 1
    for i in range(1,n + 1):
        s *= i
    return s//m
fact(10, 5)    #按照位置
fact(m=5, n=10)#按照名称

5, the return value of the function

Function can return a value, or may not, can return, may not
return 0 return value can be passed, may be any of a plurality of return value passed
multiple return values directly returns a tuple

def fact(n,m=1):
    s = 1
    for i in range(1,n + 1):
        s *= i
    return s//m, n, m
fact(10,5) #这里将会返回一个包含三个元素的元组
a,b,c = fact(10,5)

6, local variables and global variables

Rule 1: function variables are local variables, in order to use a global variable in a function, use global word reserved

n, s = 10, 100
def fact(n):
    global s  #使用global声明这是一个全局变量
    for i in range(1,n + 1):
        s *= i
    return s
print(fact(n),s)

Rule 2: Create a local variable and not as a combination of data types, the global variable is equivalent to

ls = ['F', 'f']
def func(a):
    ls.append(a)
    return
func("C")
print(ls)

7, lambda functions

lambda function returns the name of the function as a result of
lambda anonymous function is a function, i.e., without the function name
with lambda reserved words defined, the function returns the name of the result is
the function used to define simply the lambda function can be expressed in a line
using the format: < function name> = lambda <parameter>: <expression>
is equivalent to: DEF <function name> (<parameters>):
      <function name>
     return <return value>

f = lambda x,y : x + y
f(10,15)

f = lambda : "这是一个lambda函数"
print(f())

Not recommended for regular use

Published 37 original articles · won praise 17 · views 2591

Guess you like

Origin blog.csdn.net/qq_44384577/article/details/105294209