当前位置:网站首页>Basic function learning 02

Basic function learning 02

2022-07-05 03:43:00 zxr1002

Yesterday's review

function :

​ It can be regarded as a tool , Defined and then can be used repeatedly

The syntax structure of a function :

def  Function name ():
	''' Comments on functions '''
     Function body code 
    return  Return value 

Function definition and call :

​ You must use keywords when defining def

​ The definition of a function must precede the call of the function

​ The function only detects whether the syntax of the loop body code is wrong in the definition stage

Classification of functions :

​ Built in functions :python The interpreter defines its own functions in advance , It can be used directly , It will be different from the built-in method , The latter needs to be followed by specific data types

​ Custom function :

​ Empty function : No parameters , No function code block , It can be used in the early stage of project construction

​ Nonparametric functions : No parameters , It can be used directly without transferring values

​ There are parametric functions : You need to pass in parameters before using

The return value of the function :

​ The result returned by the function after execution , There can be or not .

​ No, return, The return is None

​ Yes return, There is no return value , Back again None

​ Yes return, There is a return value , What is returned is the value , Or when the variable name is returned , Then the result returns the value of its corresponding binding .

​ When a function encounters return When , It will end the execution of the function code , It is equivalent to that the loop encounters break

The parameters of the function :

​ Formal parameters : The variable names entered from left to right in the brackets of the function in the definition stage

​ The actual parameter : The data value or variable name entered from left to right in the brackets of the function at the call stage

​ The relationship between the two , It's like variable name and data value , They will temporarily bind only in the function call stage , The relationship will be dissolved after the function is executed . Dynamic binding and dynamic release

Position parameter of function :

​ Position parameter : Parameters entered in the definition phase

​ Location parameter : Parameters entered during the call phase

​ The number of position parameters should be consistent with the number of position arguments , No more, no less

Function's key argument :

​ Parameters passed in during the call phase , What shape = This form of what

​ When calling a function at the same time , A formal parameter cannot pass in multiple data at the same time

​ The method of parameter transmission is simple to complex data transmission

The default value parameter of the function :

​ In the definition phase of a function , What is the shape of the parameter passed in by the function = what

​ Set the initial value of the formal parameter directly in the function definition stage , Later, you can reset the value input during the call phase , You can also go in without transferring value , If not, the default value is the original value

Variable length parameter of function :

​ Variable length parameter : You can pass in multiple values , It breaks the limit of the number of shape participating arguments

*args---- Position parameter ,**kwargs---- Keyword parameters

Today's content

* And ** Role in arguments

def func(*args, **kwargs):
    print(args)
    print(kwargs)

'''
*  The role of : Equivalent to for Loop to get all the values in the data type behind it, and then pass them to the function at one time 
'''
func()  # ()  {}
func([1, 2, 3, 4, 5, 6])  # ([1, 2, 3, 4, 5, 6],) {}
l1 = [1, 2, 3, 4, 5, 6]
func(l1[0], l1[1], l1[2], l1[3], l1[4], l1[5])  # (1,2,3,4,5,6) {}
func(*l1)  # (1, 2, 3, 4, 5, 6) {}
'''
 there * The number is going to l1 Take out all the data values in , Then it was given to func function , It is equivalent to becoming multiple position arguments 
func(1,2,3,4,5,6)
*  Role in arguments : Will * The latter is equivalent to using a for Get out of the loop and pass it to the function at one time 
'''
s = 'good'
func(*s)  # ('g', 'o', 'o', 'd')   {}
'''func('g', 'o', 'o', 'd')'''
d = {'1': 'jason', '2': 58}
func(*d)  # ('1', '2') {}
'''
 If you add * Number , It is equivalent to using a for Loop to put... In the dictionary at one time k Take out all the values and put them in func in 
func('1','2')
'''
d1 = {'username': 'jason', 'pwd': 123}
func(**d1)  # ()  {'username': 'jason', 'pwd': 123}
func(username='jason', pwd=123)  # ()  {'username': 'jason', 'pwd': 123}
'''
**  Only applicable to dictionaries , Pass the key value pair in the dictionary into the parameter of the keyword to the function 
'''

 demand : When transferring values, you must transfer values in the form of keywords 
def func(a, b, *args):
    pass
'''
 When using this function , At least two arguments must be passed , If you send multiple data, it can only be location arguments , Cannot be keyword arguments , Because of a single * Applicable to keyword arguments , Two * Can pass in keyword arguments 
'''

def func(a, b, *args, c):
    print(a, b, *args, c)
func(1, 2, 3)
'''
 Formal parameters are required when passing arguments , Only by keyword parameters 
 In the formal parameter *args Behind 
 If there is **kwargs  That must be in front of it 
'''
def func(a, b, *args, c):
    print(a, b, args, c)
func(1, 2, 3, 4, 5, 6, 7)  #  Report errors 
func(1, 2, 3, 4, 5, 6, c=666)
def func(a, b, *args, c, **kwargs):
    pass

func(1, 2, 3, 4, 5, 6, c=123, name='jason')
d1 = {'username': 'jason', 'pwd': 123}
func(**d1)  # ()  {'username': 'jason', 'pwd': 123}
func(username='jason', pwd=123)  # ()  {'username': 'jason', 'pwd': 123}
'''
**  Only applicable to dictionaries , Pass the key value pair in the dictionary into the parameter of the keyword to the function 
'''

The name space

Introduction to namespaces

​ It is used to store the binding relationship between variable names and data values

​ Apply for a piece of memory space in memory to store jason Then bind the variable name name

​ Variable name name And value jason The binding relationship of will be stored in the namespace After using names, you can find and lock the corresponding data values in the namespace

image-20220704172800483

del name, The data value is not deleted , But the variable name and the binding relationship between the variable name and the data value

image-20220704171946693image-20220704172556632

Namespace classification

Built in namespace

​ python The space created immediately after the interpreter runs , All the names that can be used directly in the process of writing code are in this space ,eg:len()、print()、input()......

​ Life cycle : The interpreter runs ( establish ) The interpreter is off ( The destruction )

Global namespace

​ py The names generated in the process of running the code in the file will be stored in this space

​ Variable names in ordinary code 、 The variable name in the branch structure 、 The variable name in the loop structure 、 Define the function name of the function

​ Life cycle :py File run ( establish ) py End of file ( The destruction )

Local namespace

​ The names generated during the operation of the function body code will be stored in this space

​ Life cycle : Function body code runs ( establish ) End of function body code ( The destruction )

​ a key : Find out which namespace you are in before the name

'''
 You can save names in all three namespaces , If there is a name, there are all three spaces , Which one 
1. Currently in the global namespace , First, check whether there is in the global namespace , Then look at the built-in namespace 
2. Currently in the local namespace , First, check whether there is in the local namespace , Then look at the global namespace , Finally, look at the built-in namespace 
3. By default, the search order of names cannot be reversed, only , From local to global to built-in 
'''

len = ' I am in the global namespace len'
def func():
    len = ' I'm in the local namespace len'
    print(len)  #  I'm in the local namespace len
func()
print(len)  #  I am in the global namespace len


len = ' I am in the global namespace len'
def func():
    # len = ' I'm in the local namespace len'
    print(len)  #  I am in the global namespace len
func()
print(len)  #  I am in the global namespace len

The scope of the namespace

Built in namespace : It can be used anywhere in the program ( Global availability )

Global namespace : It can be used anywhere in the program ( Global availability )

Local namespace : In their respective local space can be used ( Partially effective )

Local namespace complexity

x = 1
def func1():
    x = 2
    def func2():
        x = 3
        def func3():
            x = 4
			print(x)  # 4
         func3()
     func2()
 func1()

x = 1
def func1():
    x = 2
    def func2():
        x = 3
        def func3():
			print(x)  # 3
         func3()
     func2()
 func1()

x = 1
def func1():
    def func2():
        def func3():
			print(x)  # 1
         func3()
     func2()
 func1()

def func1():
    def func2():
        def func3():
			print(x)  #  Report errors 
         func3()
     func2()
 func1()

#  In nested relationships , To find the value, you need to look out from the current position layer by layer 
image-20220704193629563
#   Unexpected special circumstances ,
def func1():
    x = 4
    def func2():
        x = 4
        def func3():
            print(x)  # 1
            x = 4
        func3()
    func2()
func1()
'''
 In the definition phase, the function only detects the syntax and does not execute the code , But at this time, it has confirmed who to ask for the name first , It detects func3 There is X, But when implementing, it is implemented from top to bottom , here x Not yet defined , You can only report an error 
'''

global And nonlocal keyword

money = 999  #  There is a global 
def func():
    money = 1000  #  At this time money about func This local namespace is a new name , Has its own namespace 
func()
print(money)  # 999   there money At this time, the location is in the global namespace , So what we are looking for is in the global namespace money

money = 999  #  There is a global 
def func():
    money = 1000
    print(money)  # 1000
func()
print(money)  # 999

'''
 Under normal circumstances   New names appearing in the local namespace will be stored in the local namespace 
 But sometimes you need to change the name of the global namespace in the local namespace 
'''
money = 999  #  There is a global 
def func():
    global money  #  Used in local namespaces money No longer in the local namespace , It's global , Then on money Anything you do affects the overall situation money
    print(money)  # 1000
func()
print(money)  # 999

s = '$jason$'
def func():
    global s
    s = 'jason'
    res = s.split('$')
func()
print(s)  # jason
"""
 Locally modify the immutable type data in the global namespace   Keyword required global Statement 
 If it's ok 
def func1():
    x = 1
    l1 = [1,2]
    def func2():
# global x #   Local should be global 
        # nonlocal x
        x = 999
        l1.append(666)
    func2()
    print(x)
    print(l1)
func1()
"""
nonlocal  Modify immutable types in the outer local namespace in the memory local namespace 
"""

There are many ways to use function names

1. Function names can be used to assign values multiple times ( The function name is consistent with the variable name )

name = func  #  Give Way name Also points to functions func The memory address of the block of function body code pointed to 
name()
name1 = name
name1()  #  It can also be adjusted 

2. The function name is used as the argument of the function

def index(a):
    print(a)
    a()
index(123)
name = 'jason'
index(name)
index(func) 

3. The function name can also be used as the return value of the function

def index():
    return func
res = index()
print(res)
res()

4. The function name can also be used as the data value in the container type

l1 = [1,2,3,4,func]
print(l1)
l1[-1]()

Homework :

def regisetr():
    username = input(' Please enter a user name :').strip()
    password = input(' Please input a password :').strip()
    with open(r'userinfo.txt', 'r', encoding='utf8') as read_f:
        for info in read_f:
            #  Circular cutting index finds the name 
            data_name = info.split('|')[0]
            if username == data_name:
                print(' The user already exists ')
                break
        else:
            # password = input(' Input password :').strip()
            #  Change the user name and password to string format 
            user_data = '%s|%s\n' % (username, password)
            #  Write to file 
            with open(r'userinfo.txt', 'a', encoding='utf8') as write_f:
                write_f.write(user_data)
            print(f'{username} Registered successfully ')
            return True


def login():
    username = input(' Please enter a user name :').strip()
    password = input(' Please input a password :').strip()
    with open(r'userinfo.txt', 'r', encoding='utf8') as read_f:
        for info in read_f:
            #  Cut the user and password 
            data_name, data_pwd = info.split('|')
            #  Determine whether the input is correct 
            if username == data_name and password == data_pwd.rstrip('\n'):
                print(' Login successful ')
                break
        else:
            print(' Wrong user name or password ')
def back():
    print(' Welcome to come again next time ')

func_dict = {'1': regisetr,
             '2': login,
             '3': back,
             }

while True:
    print('''
        1. User registration function 
        2. User login function 
        3. sign out 
    ''')
    funct_choice = input(' Please enter the operation to be performed :').strip()
    if funct_choice in func_dict:
        func_name = func_dict.get(funct_choice)
        func_name()
    else:
        print(' There is no function number ')

原网站

版权声明
本文为[zxr1002]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050329034736.html