current position:Home>Introduction to Python learning functions

Introduction to Python learning functions

2022-02-02 12:06:59 FamilyYan

One 、 Function introduction

  • A function is also an object
    - An object is an area of memory dedicated to storing data
    - Function can be used to save some executable code , And when needed , Make multiple calls to these statements .
    - Create a function :
    def Function name ([ Shape parameter 1, Shape parameter 2,… Shape parameter n]) :
    Code block
    - The function name must conform to the specification of the symbolic identifier
    ( It can contain letters 、 Numbers 、 Underline 、 But it can't start with a number )
    - The code saved in the function does not execute immediately , You need to call the function code to execute
    - Call function :
    Function object ()
    - Defining a function is generally to achieve a certain function
#  Define a function , Find the sum of two numbers 
#  When defining a function , Specify parameter 
def fn(a, b):
    print(a + b)

#  Call function 
#  When you call a function , To pass arguments 
fn(10, 20)

 Console output :30

Two 、 The parameters of the function

  • When you define a function , Can be in the function name after () Define different numbers of formal parameters in ,
    Use... Between multiple parameters , separate
    - Shape parameter ( Formal parameters ), Defining formal parameters is equivalent to declaring variables inside a function , But no assignment
    - Actual parameters ( The actual parameter )
    - If the function definition , Formal parameters are specified , Then you have to pass arguments when you call a function ,
#  Find the product of any three numbers 
def mul(a,b,c):
    print(a*b*c)
    
mul(1,2,3)     # 6

2、 When defining formal parameters , You can specify default values for formal parameters

After specifying the default value , If the user passes a parameter, the default value has no effect
If the user does not pass , Then the default value will take effect


def fn(a=5, b=10, c=20):
    print('a =',  a,  'b = ',  b, 'c = ', c)

fn(60)  # a = 60 b =  10 c =  20

3、 How arguments are passed
Mode one : Positional arguments

Location parameter is to copy the argument of the corresponding location to the formal parameter of the corresponding location
The first argument is assigned to the first formal parameter , The second argument is assigned to the second formal parameter ...
fn(1 , 2 , 3)

Mode two : Key parameters

Key parameters , It can be passed in the order not defined by formal parameters , And pass the parameter directly according to the parameter name
Location parameters and keyword parameters can be mixed .
When you mix keywords and positional parameters , The position parameter must be written before .

def fn(a, b, c):
    print('a =', a, 'b = ', b, 'c = ', c)


fn(10, 20, 30)    #  Location reference 
fn(c=30, a=10, b=20)  #  Pass the key words to 
#  A mixture of 
fn(b=20, 10, 30)  #  Will report a mistake 
fn(10, c=30, 20)  #  Will report a mistake 
fn(10, c=30, b=20)

4、 Function is called , The parser doesn't check the type of arguments
Arguments can pass any type of object .


def fn(a, b, c):
    print('a =', a, 'b = ', b, 'c = ', c)
    
def fn2(a):
    print('a =',a)

 Function is called , The parser doesn't check the type of arguments 
 Arguments can pass any type of object 
b = 123
b = True
b = 'hello'
b = None
b = [1,2,3]

# fn2(b)    
fn2(fn) # a= <function fn at 0x7f9de75c6e18>

5、 Reassign a variable within a function

def fn4(a):
    #  Reassign the formal parameter in the function , It doesn't affect other variables 
    a = 20
    print('a =', a)


c = 10
fn4(c)  
print('c =', c)

 Console printing :
c = 10
a = 20
def fn4(a):
    # a It's a list , Try to modify the elements in the list 
    #  If the formal parameter executes an object , When we modify an object through formal parameters 
    #    Will affect all variables that point to the object 
    a[0] = 30
    print('a =', a, id(a))


c = [1, 2, 3]
fn4(c)
print('c =', c, id(c))

 Console printing :
a = [30, 2, 3] 140311730616712
c = [30, 2, 3] 140311730616712

When a mutable object is passed , You don't want the internal operation of the function to affect the external value , Then you can choose to transfer a copy of the object :

def fn4(a):
    # a It's a list , Try to modify the elements in the list 
    #  If the formal parameter executes an object , When we modify an object through formal parameters 
    #    Will affect all variables that point to the object 
    a[0] = 30
    print('a =', a, id(a))


c = [1, 2, 3]
#   Deliver a copy 
fn4(c.copy())  
#  Or slices :fn4(c[:])
print('c =', c, id(c))

 Console printing :
a = [30, 2, 3] 140284417307656
c = [1, 2, 3] 140284417309064

3、 ... and 、 Indefinite length parameter

1、 Indefinite length parameter definition

When you define a function , You can add a *, So this parameter will get all the arguments . He will save all the arguments to a tuple .
for example :a,b,*c = (1,2,3,4,5,6)
a=1,b=2,c=(3,4,5,6)

2、 Pack :*a Will accept all positional arguments , And these arguments will be saved in a tuple ( Pack )
def fn(*a):

def fn(*a):
    print("a =", a, type(a))
    
fn()  # a = () <class 'tuple'>
fn(1,2)  # a = (1, 2) <class 'tuple'>

def sum(*nums):
    #  Define a variable , To save the results 
    result = 0
    #  Traversal tuples , And add up the numbers in the tuple 
    for n in nums :
        result += n
    print(result)

sum(123,346)  # 469
sum(123,456,789,10,20,30,40) # 1468

3、 Characteristics of indefinite length parameters

There can only be one parameter with an asterisk
Parameters with an asterisk , It can be used with other parameters
Give me the first parameter a, The second parameter is b, Save the rest to c In the tuple of
def fn2(a,b,*c):
print(‘a =’,a)
print(‘b =’,b)
print(‘c =’,c)
Variable parameters don't have to be written at the end , But notice , belt * All parameters after the parameters of , Must be passed as a keyword argument , Otherwise, an error will be reported
Give me the first parameter a, The rest of the positional parameters are given to b tuples ,c Keyword parameters must be used

def fn2(a, *b, c):
    print('a =', a)
    print('b =', b)
    print('c =', c)

fn2(1,2,3,4,5) # TypeError: fn2() missing 1 required keyword-only argument: 'c'
fn2(1, 2, 3, 4, c=5)
 Console printing :
a = 1
b = (2, 3, 4)
c = 5


 All the position parameters are given to a,b and c Keyword parameters must be used 
def fn2(*a,b,c):
    print('a =',a)
    print('b =',b)
    print('c =',c)
  fn2(3,4,5,6,b=10,c=50)
#  If you write one directly at the beginning of a formal parameter *, All our parameters must be passed in the form of keyword parameters 
def fn2(*,a,b,c):
    print('a =',a)
    print('b =',b)
    print('c =',c)
  fn2(a=3,b=4,c=5)

4、** Two stars define indefinite length parameters

 One *  Definition 
# * Formal parameters can only receive positional parameters , Instead of receiving keyword parameters 
def fn3(*a) :
     print('a =',a)
     
fn3(b=1,d=2,c=3,e=10,f=20)   # TypeError: fn3() got an unexpected keyword argument 'b'

Use **

** Formal parameters can receive other keyword parameters , It will save these parameters into a dictionary
Dictionary key It's the name of the parameter , Dictionary value It's the value of the parameter
** Formal parameters can only have one , And it must be written at the end of all the parameters


def fn3(**a):
    print('a =', a)

fn3(b=1, d=2, c=3, e=10, f=20)   # a = {'b': 1, 'd': 2, 'c': 3, 'e': 10, 'f': 20} <class 'dict'>

# Formal parameters can only have one , And it must be written at the end of all the parameters 
def fn3(b, c, **a):
    print('a =', a, type(a))
    print('b =', b)
    print('c =', c)

fn3(b=1, d=2, c=3, e=10, f=20) 
 Console printing :
a = {'d': 2, 'e': 10, 'f': 20} <class 'dict'>
b = 1
c = 3

5、 Unpacking of parameters
Split the values in a sequence , Pass as an argument

def fn4(a,b,c):
    print('a =',a)
    print('b =',b)
    print('c =',c)

#  Create a tuple 
t = (10,20,30)
fn4(*t)    
 Console printing :
a = 10
b = 20
c = 30

#  When passing arguments , You can also add an asterisk before the parameters of the sequence type , In this way, he will automatically pass the elements in the sequence as parameters in turn 
#  Here, the number of elements in the sequence must be consistent with the number of formal parameters 

def fn4(a, b, c):
    print('a =', a)
    print('b =', b)
    print('c =', c)


#  Create a dictionary 
d = {'a': 100, 'b': 200, 'c': 300}
#  adopt  ** To unpack a dictionary 
fn4(**d)
 Console printing :
a = 100
b = 200
c = 300

Four 、 Return value

1、 Return value definition

Return value , The return value is the result returned after the function is executed .
Can pass return To specify the return value of the function .
The values returned by the function can be used , You can also receive the return value of the function through a variable .

def fn():
    #  Function nested function 
    def fn2() :
        print('hello')

    return fn2 #  The return value can also be a function 
r = fn()
print(r)  #<function fn.<locals>.fn2 at 0x7ff4cccc66a8>

# If you just write one return  perhaps   Don't write return, It's equivalent to return None
def fn2() :
    a = 10
    return
r2 = fn2()  
print(r2) # None


#  In the function ,return After the code will not be executed ,return  Once the function is executed, it ends automatically 
def fn3():
    print('hello')
    return
    print('abc')

fn3()  # hello

2、berak、continue、return The difference between using in a function

#  Use break
def fn4():
    for i in range(5):
        if i == 3:
             break  # Used to exit the current loop 
        print(i)
    print(' Loop execution complete !')
    Console print results :
   0
   1
   2
    Loop execution complete !


#  Use continue
def fn4():
    for i in range(5):
        if i == 3:
            continue  # Used to skip the current loop 
        print(i)
    print(' Loop execution complete !')

fn4()
    Console print results :
   0
   1
   2
   4
    Loop execution complete !

# Use return
def fn4():
    for i in range(5):
        if i == 3:
            return  #  To end a function 
        print(i)
    print(' Loop execution complete !')

fn4()
 Console print results :
0
1
2

3、fn5 and fn5() The difference between

def fn5():
    return 10

# fn5  and  fn5() The difference between 
print(fn5) # fn5 Is a function object , Print fn5 It's actually printing function objects  <function fn5 at 0x05771BB8>
print(fn5()) # fn5() It's calling functions , Print fn5() It's actually printing fn5() The return value of the function  10

5、 ... and 、 When defining a function, write a document string

docstring (doc str)
When you define a function , You can write a document string inside the function , The document string is the description of the function
When we write a document string , You can go through help() Function to see the description of the function
The document string is very simple , In fact, writing a string directly on the first line of the function is the document string

1、 adopt help View the document string of the system's own function
help(print) # obtain print() Function instructions
2、 Write the document string when customizing the function

def fn(a:int,b:bool,c:str='hello') -> int:
    '''
     This is an example of a document string 

     Function function :.....
     The parameters of the function :
        a, effect , type , The default value is ....
        b, effect , type , The default value is ....
        c, effect , type , The default value is ....
    '''
    return 10

copyright notice
author[FamilyYan],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202021206566792.html

Random recommended