python basic learning 11 ---- functions

Keywords: Python Asterisk

1, Definition of function

def function name (parameter list):
    Function body
    return statement

Return statement without writing or adding any object after it is return None

2, Parameters of function

No parameter

def func1():
    print("No parameters")

One parameter

def func1(a):
   return a

Multiple parameters

def func1(a,b,c):
   return a+b+c

Necessary parameters

Parameters must be passed in the correct order and quantity

def func1(name,age,job):
   print("name:%s age:%d job:%s"%(name,age,job))
func1("sfencs",20,"IT")

Key parameters

def func1(name,age,job):
   print("name:%s age:%d job:%s"%(name,age,job))
func1(age=20,name="sfencs",job="IT")

Default parameters

The default parameter must be placed after the required parameter

def func1(name,age,job="IT"):
   print("name:%s age:%d job:%s"%(name,age,job))
func1("sfencs",20)
func1("Alan",25,"teacher")

Indefinite length parameter

Parameter with an asterisk*

def func1(*args):
    print(args)
func1(1,2,3,"sfencs")#(1, 2, 3, 'sfencs') in tuple form

Parameter with two asterisks**

def func1(**args):
    print(args)
func1(age=20,name="sfencs",job="IT")#{'age': 20, 'name':'sfencs', 'job':'It '} saved as a dictionary

When defining the parameters of a function, please define the parameters in the order of required parameter, default parameter, indefinite length parameter with one asterisk and indefinite length parameter with two asterisks

3, Parameter passing

Immutable type

def func1(a):
    a=5
b=10
func1(b)
print(b)#Output is 10.

Variable type

def func1(list1):
    list1.append("sfencs")
list2=[1,2,3]
func1(list2)
print(list2)#[1, 2, 3, 'sfencs']list2 will change

4, Variable scope

L (Local) Local scope
In functions other than E (closing) closure functions
G (Global) Global scope
B (built in) built in scope

Search by L -- > e -- > G -- > b

Internal scope modifying external scope variables

global

count=20
def function() :
    global count#If you don't add this sentence, you will make a mistake
    print (count)#20
    count=5
    print(count)#5
function()
print(count)#5

nonlocal 

Modify nested scope

def function1() :
    count=20
    def function2():
        nonlocal count
        count=5
        print(count)#5
    function2()
    print(count)#r at this time, the output is 5. If nonlocal count is not added, the output is 20
function1()

5, Recursive function

#Fibonacci sequence is 0,1,1,2,3,5,8,13,21,34
def fibon(n):
    if n<=2 :
        return n-1
    return fibon(n-1)+fibon(n-2)
print(fibon(7))#The seventh number in the output sequence, which is 8

Posted by kelseyirene on Thu, 02 Jan 2020 20:59:44 -0800