s21day12 python notes

I. middle and high level functions

1.1 function can do return value

#Example:
def func():
    print(123)
def bar():
    return func

v = bar()
v()

1.2 closure

  1. Concept: create an area for a function and maintain its own data, which can be easily called later
  2. Application scenario:
    • Decorator
    • SQLAlchemy source code
#Example:
name = 'oldboy'
def bar(name):
    def inner():
        print(name)
    return inner
v1 = bar('alex') # { name=alex, inner }  # Closure, which creates an area for the function (internal variables for its own use) to provide data for its later execution.
v2 = bar('eric') # { name=eric, inner }
v1()
v2()
#Exercise questions:
#First question
name = 'alex'
def base():
    print(name)
def func():
    name = 'eric'
    base()
func() 
    
# Second questions
name = 'alex'
def func():
    name = 'eric'
    def base():
        print(name)
    base()
func()

# Third questions
name = 'alex'
def func():
    name = 'eric'
    def base():
        print(name)
    return base 
base = func()
base()

#Note: when and by whom were functions created?
#Example:
info = []
def func():
    print(item)   
for item in range(10):
    info.append(func)

info[0]()


#Interview questions
info = []
def func(i):
    def inner():
        print(i)
    return inner
for item in range(10):
    info.append(func(item))

info[0]()
info[1]()
info[4]()

1.3 higher order function

  1. Passing functions as arguments
  2. Treat function as return value
  3. Note: assign values to functions

II. Built in function supplement

2.1 mathematics related supplement

  • pow(): index

    v = pow(2,3)      #Equivalent to 2 * * 3
    print(v)         # 8
  • round(): keep several decimal places, keep integer by default, and round

    v = round(1.127,2)       #The second number represents the number of decimal places reserved. The default value is None
    print(v)         # 1.13 rounding

2.2 coding related

  • chr(): converts a decimal number to a corresponding string in unicode encoding

  • ord(): find the corresponding decimal system in unicode encoding according to characters

    #Application: generate random verification code
    import random          # Import a module 
    def get_random_code(length=6):
        data = []
        for i in range(length):
            v = random.randint(65,90)
            data.append(chr(v))
        return  ''.join(data)
    
    code = get_random_code()
    print(code)

2.3 built in function advanced

  • Map (function, iteratable object): execute together

    • Loop through each element (the second argument), then have each element execute the function (the first argument), save the result of each function execution to a new list, and return
    #Example:
    v1 = [11,22,33,44]
    result = map(lambda x:x+100,v1)
    print(list(result)) 
  • Filter (function, iteratable object): filter

    #Example:
    v1 = [11,22,33,'asd',44,'xf']
    
    def func(x):
        if type(x) == int:
            return True
        return False
    result = filter(func,v1) 
    print(list(result))
    
    # Use lambda expression:
    result = filter(lambda x: True if type(x) == int else False ,v1)
    print(list(result))
    # Amount to:
    result = filter(lambda x: type(x) == int ,v1)
    print(list(result))
  • Reduce (function, iteratable object): get the result

    import functools
    v1 = ['wo','hao','e']
    def func(x,y):
        return x+y
    result = functools.reduce(func,v1) 
    print(result)
    
    # Use lambda expression:
    result = functools.reduce(lambda x,y:x+y,v1)
    print(result)

Three, module

3.1 random: random number module

import random    # Import a module 
v = random.randint(Start,termination)    # Get a random number

#Example: generate random verification code
import random     
def get_random_code(length=6):
    data = []
    for i in range(length):
        v = random.randint(65,90)
        data.append(chr(v))
    return  ''.join(data)

code = get_random_code()
print(code)

3.2 hashlib: encryption module

# Encrypt the specified string
import hashlib     # Import a module

def get_md5(data):          # md5 encryption function  
    obj = hashlib.md5()
    obj.update(data.encode('utf-8'))
    result = obj.hexdigest()
    return result

val = get_md5('123')
print(val)

# Salt addition
import hashlib

def get_md5(data):
    obj = hashlib.md5("sidrsdxff123ad".encode('utf-8'))            # Salt addition
    obj.update(data.encode('utf-8'))
    result = obj.hexdigest()
    return result

val = get_md5('123')
print(val)
# Application: user registration + user login
import hashlib
USER_LIST = []
def get_md5(data):                   # md5 encryption function 
    obj = hashlib.md5("12:;idrsicxwersdfsaersdfs123ad".encode('utf-8'))         # Salt addition
    obj.update(data.encode('utf-8'))
    result = obj.hexdigest()
    return result

def register():                      # User registration function
    print('**************User registration**************')
    while True:
        user = input('enter one user name:')
        if user == 'N':
            return
        pwd = input('Please input a password:')
        temp = {'username':user,'password':get_md5(pwd)}
        USER_LIST.append(temp)

def login():                          # User login function
    print('**************User login**************')
    user = input('enter one user name:')
    pwd = input('Please input a password:')
    for item in USER_LIST:
        if item['username'] == user and item['password'] == get_md5(pwd):
            return True

register()
result = login()
if result:
    print('Landing successfully')
else:
    print('Landing failed')

3.3 getpass: it can only run at the terminal

import getpass        # Import a module

pwd = getpass.getpass('Please input a password:')
if pwd == '123':
    print('Input correct')

Tags: Python Lambda encoding

Posted on Thu, 28 Nov 2019 10:57:16 -0800 by developer