Python introductory functions

1. Initial Identity Function

1.1 What is a function?

< 1 > Encapsulating a function into a space is a function

< 2 > Reduce duplicate code

1.2 Define Functions

Def -- Keyword in Python

() -- Format requirements must be written

:--End of statement

def len():    
    Function Body
def my_len():    
    n = 0    
    for i in dic:        
    n += 1    
    print(n)

1.3 Function Call

The function name +() means calling the function.

def yue():    
    print("Take out your cell phone")    
    print("Open the Wechat")    
    rint("Shake a shake")    
    print("Have a chat")    
    print("Do you want to have an appointment??")    
    print("....")
yue()
yue()

Process-oriented:

print("Take out your cell phone")
print("Open the Wechat")
print("Shake a shake")
print("Have a chat")
print("Do you want to have an appointment??")
print("....")
print("go to work")
print("Take out your cell phone")
print("Open the Wechat")
print("Shake a shake")
print("Have a chat")
print("Do you want to have an appointment??")
print("....")
print("Check it out")

Function-oriented programming:

def work():    
    print("Turn on the computer")    
    print("Check Mail")    
    print("Open and find the Wechat")    
    print("Talk in groups")    
    print("Start Code")    
    print("Finish off")    
    print("Go off work")
def yue():    
    print("Take out your cell phone")    
    print("Open the Wechat")    
    print("Shake a shake")    
    print("Have a chat")    
    print("Do you want to have an appointment??")    
    print("....")
yue()
work()
yue()
print("Check it out")
yue()
print("6 Hot and hot money")
yue()
print("Rest meeting,Last shift")

Return value of 1.4 function

def yue():   
    print("Turn on your cell phone")    
    print("Open the Wechat")   
    print("Open up the people nearby")    
    print("Have a chat")    
    print("See you.")    
    print("......")    
    return 1,2,3,4,5    
    print(1111)
girl = yue()
print(girl)

(1) The return value of the function, which is returned to the caller of the function.

Return value (return value)

(2)return:

< 1 > can return any type of data
<2> return is tuple when it returns more than one content
<3> does not execute below return and terminates the current function
<4> return returns None if it does not write or if it does not write the value after it.

Function name +()

Starter function

Accept the return value

Parameters of 1.5 Function

def yue(app1,app2,app3,app4):      # Formal parameter       
    print("Turn on your cell phone")    
    print(f"open{app1} {app2}")    
    print("Have a chat")    
    print("See you.")    
    print("......")
yue("WeChat","Exploration","Unfamiliar Street","soul")        # Real reference
def yue(a,b,c,app1="WeChat"):     # Formal parameter      
    print("Turn on your cell phone")    
    print(f"open{a} {app1}")    
    print("Have a chat")    
    print("See you.")    
    print("......")
yue("Exploration","Unfamiliar Street","WeChat")      # Real reference
def yue(a,b,c,a1="WeChat"):     # Formal parameter       
    print("Turn on your cell phone")    
    print(f"open{a} {b} {c} {a1}")    
    print("Have a chat")    
    print("See you.")    
    print("......")
yue(11,c=5,b=1)       # Real reference

Trinary Operator* (Trinary Operator): (Only if else is supported)

The result of the condition being tenable The result of the condition not being tenable

def func(a,b):    
    return a if a > b else b
print(func(6,9))

def info(name,age,job,moeny,sex="male"):    
    print(f"Full name:{name} Age:{age} Gender:{sex} post:{job} salary:{moeny}")
while True:    
    name = input("name:")     # rimo    
    age = input("age:")       # 89    
    sex = input("sex(Male return):") # female    
    job = input("job:")          #  wc    
    money = input("moeny:")      # 10    
    if sex == "female":        
        info(name,age,job,money,sex)    
    else:        
        info(name, age, job, money)

(1) Formal parameters:

<1> Location parameters:

One-to-one correspondence

<2> Default parameters: When a function is defined, the default parameters are written in parentheses

The default parameters are used instead of passing parameters, and the passed parameters are used when passing parameters.

(2) References:

<1> Location parameters:

One-to-one correspondence

<2> Keyword parameters:

Reference by name

(3) Mixing parameters:

Use location parameters with keyword parameters

Location parameter > default parameter (keyword parameter)

Formal parameters: The parameters in parentheses during the function definition phase are called formal parameters.

Arguments: The parameters in parentheses during the function call phase are called arguments

Passing parameters: The process of passing parameters to formal parameters is called passing parameters.

2. Functional progression:

def eat(a,b,c,d,e,f):    
    print(a,b,c,d,e,f)
eat("Spicy Hot Pot","Big pancakes","Big pancakes","Big waist","Leek","Lamb Spine Hot Pot")

How to solve the problem of too many parameters?

2.1 Dynamic position parameters:

def eat(*args):    # Function Definition Stage * Aggregation (Packaging)    
    print(args)    # tuple    
    print(*args)   # Dispersion (unpacking) of * in function body
eat("Spicy Hot Pot","Big pancakes","Big pancakes","Big waist","Leek","Lamb Spine Hot Pot")
def eat(a,b,*c):       #Location parameter > dynamic position parameter
    print(a)    
    print(b)    
    print(c)     # tuple
eat("noodle","Steamed Rice","Steamed buns","Big cake")
def eat(a,b,*args,d=2,**c):  # Location parameter > Dynamic position parameter > Default parameter > Dynamic default parameter
    print(a)
    print(b)
    print(d)
    print(args)     # tuple
    print(c)        # dict
eat("noodle","Steamed Rice","Big pancakes","Big pancakes",a1=1,b1=2)        # Location > Keyword
def eat(*args,**kwargs):  # (universal reference)
    print(args) # tulpe
    print(kwargs) #
lst = [1,23,4,6,7]
dic = {"key1":1,"key2":3}
//Application scenarios
eat(lst,dic)

eat(*lst,**dic) # eat(1,23,4,6,7,"key1"=1,"key2"=2)

Summary:

<1> * args (aggregation location parameter) The names used by all the big guys can be modified, but not recommended.

<2> ** kwargs (aggregate keyword parameters) The names used by all the big guys can be modified, but it is not recommended.

Definition stages of functions * and ** are aggregates

In the body of a function * is to break up,* args to break up the elements in the tuple,* kwargs to get the keys of the dictionary

2.2 Parameters:

< 1 > Location parameter

Dynamic Position Parameters: The position parameters are executed first, the position parameters are accepted and the additional parameters are accepted by the dynamic position parameters, and a tuple is obtained.

<2> Default parameter

Dynamic keyword parameters (default): First, the default parameters are executed, then the default parameters are accepted by the additional default parameters, and a dictionary is obtained.

Arguments and function bodies:

  • * To scatter
  • ** Can be used when referencing

Notes to the 2.3 function:

def a(a:int,b:int):
    """
    //Summation
    :param a: int
    :param b: int
    :return:  int
    """
    return a + b

def b(a:int,b:int):
    """
    //Seeking difference
    :param a: int
    :param b: int
    :return:  int
    """
    return a - b

(1) Function name. doc

(2) Function name. name view function name

2.4 Namespace

(1) Built-in space: the space provided by the Python interpreter

(2) Global space: global space is written at the top of py file

(3) Local space: the function body is the local space

<1> Loading order:

Built-in space

Global space

Local space

def func():
    a = 1
    print(a)
func()
<2> Value order:

Local space

Global space

Built-in space

a = 10
def func():
    print(a)
func()

(4) Scope:

Global scope: global + built-in

Local scope: local

Scope's role is to protect data security

The nesting of 2.5 functions:

No matter where it is, a function name () is calling a function.

Mixed nesting:

def f1():
    print(11)
def f2():
    print(22)
    f1()
def f3():
    print(33)
    f1()
def run():
    f3()
    f2()
    f1()
run()

def foo(a):
    a = 10
    def f1(b):
        c = b
        def foo(c):
            print(c)
            print(foo.__doc__)
        foo(c)
        print(b)
    f1(a)
    print(a)
foo(25)

2.6 global: Modify the global only, and create one if not

a = 10
def func():
    global a
    a = a - 6
    print(a)
print(a)
func()
print(a)

2.7 nonlocal: Modify only the local, modify the nearest layer from nonlocal, the upper layer does not continue to look up the upper layer, only the local, no errors will be reported.

a = 100
def func():
    b = 10
    def foo():
        b = a
        def f1():
            nonlocal b
            b = b + 5
            print(b)  # 105
        f1()
        print(b)  # 105
    foo()
    print(b) # 10
func()
print(a)         # 100

enumerate()# Enumeration defaults to starting from 0. The first parameter is an iteratable object and the second object is the starting value.

3. The First Kind of Objects of Functions and Their Use

(1) Function names can be assigned to variables as values:

def func():
    print(1)
print(func)          # Memory address of function
a = func
print(a)
a()

(2) Function names can be used as elements in containers:

def login():
    print("This is login.")
def register():
    print("This is registration.")
def index():
    print("This is the homepage of Blog Garden.")
msg = """
1 Sign in
2 register
3 homepage
"""
choose = input(msg)   # 1
if choose.isdecimal():
    if choose == "1":
        login()
    elif choose == "2":
        register()
    elif choose == "3":
        index()

Improvement:

def login():
    print("This is login.")
def register():
    print("This is registration.")
def index():
    print("This is the homepage of Blog Garden.")
dic = {"1":login,"2":register,"3":index}
msg = """
1 Sign in
2 register
3 homepage
"""
choose = input(msg)   # 1
if choose.isdecimal():
    if dic.get(choose):
        dic[choose]()
    else:
        print("Please enter correctly!")

(3) Function names can be used as parameters of functions:

def func(a):
    print(111)
    a()
def foo():
    print(222)
func(foo)

(4) The function name can be used as the return value of the function:

def func():
    def foo():
        print(111)
    return foo
a = func()
a()
func()()  # foo()

Practice:

def f1(c):
    def a():
        def f3():
            print(3333)
            return [f3,a,f1]
        print(11)
        return f3()
    ret = a()
    return c(ret)

def aa(b):
    print(111)
    return b
print(f1(aa))

4. Anonymous function == one sentence function (one line function)

Anonymous functions are named lambda

(1)lambda x:x

<1> lambda keyword

<2> x is the formal parameter of ordinary function (position, keyword........................) It can not receive parameters, it can not write.

<3>: The x behind the X colon is the function value of a normal function (only one data type can be returned), and must have a return value.

print((lambda x:x+6)(5))

f = lambda x:x+6
print(f.__name__)

f = lambda x,y,z,b=1:x,y,z,b
print(f(1,2,3))

print([lambda :5][0]())
print((lambda :5)())
a = lambda :5
a()

lst = [lambda :i for i in range(5)]
print(lst[0]())
lst = [lambda :i for i in range(5)]
print(lst[0]())

//Interview question disassembly:
lst = []
for i in range(5):
    def func():
        return i
    lst.append(func)
lst = [] # [lambda x:x+1,lambda x:x+1]
for i in range(2):
    lst.append(lambda x:x+1)
print(lst[-1](5))

lst = [lambda x:x+1 for i in range(5)]
print(lst[0](5))

tu = (lambda :i for i in range(3))
print(next(tu)())
print(next(tu)())
print(next(tu)())

def func():
    for i in range(3):  # i = 0 1 2
        def foo():      # foo1  foo2  foo3
            return i
        yield foo       # foo1  foo2  foo3
g = func()
print(next(g)())  # foo1
print(next(g))  # foo2
print(next(g))  # foo3

lst = [lambda :i for i in range(3)]
print(lst[0]())

tu = (lambda :i for i in range(3))
print(next(tu)())
lst = [lambda x:x+5 for i in range(2)]
print([i(2) for i in lst])

lst = [] # [lambda x:x+5,lambda x:x+5]
for i in range(2):
    lst.append(lambda x:x+5)
new_lst = []
for i in lst:
    new_lst.append(i(2))
print(new_lst)
lst = (lambda x:x+5 for i in range(2))
print([i(2) for i in lst])

def func():
    for i in range(2):
        f = lambda x: x + 5
        yield f
g = func()
lst = []
for i in g:
    lst.append(i(2))
print(lst)
lst = [lambda x:x*i for i in range(2)]
print([i(2) for i in lst])  #[2,2]

lst = [] # [lambda x:x*i,lambda x:x*i]
for i in range(2):
    lst.append(lambda x:x*i)
# print(i)
new_lst = []
for em in lst:
    new_lst.append(em(2))
print(new_lst)
lst = (lambda x:x*i for i in range(2))
print([i(2) for i in lst])  #[0,2]

def func():
    for i in range(2):
        f = lambda x:x*i
        yield f
g = func()
lst = []
for i in g:
    lst.append(i(2))
print(lst)

Keywords: Python Lambda Programming REST

Added by blackwidow on Fri, 30 Aug 2019 06:43:26 +0300