Python -- 3 basic syntax

Posted by cainfool on Wed, 09 Feb 2022 08:16:54 +0100

catalogue

 

1, Function

1. Function function

2. Use steps of function

3. Function parameters

4. Function return value function

5. Application: calculate the sum of any two numbers and save the results

6. Documentation for functions

7. Nested calls to functions

8. Variable scope

9. Function parameters

10. Unpacking

11. Quote

2, Application: college management system

3, Recursion

1. Characteristics of recursion

4, lambda expression

2. Parameter form of lambda

3. Application of lambda

5, Higher order function

1. Built in higher order function

1, Function

1. Function function

A function is a piece of code with independent functions, which is integrated into a whole and named. The corresponding requirements can be completed by calling this name at the required position. In the process of function development, code reuse can be realized more efficiently.

2. Use steps of function

  • Define function

def function name (parameter):

Code

  • Call function

Function name (function)

Note: in different requirements, parameters are optional; In Python, functions must be defined before use.

3. Function parameters

# While defining the function, the parameters a and b of receiving user data are defined. A and b are formal parameters
def add_num1(a,b):
    """ Function parameters """
    result = a + b
    print(result)

#When calling the function, the real data 10 and 20 are passed in, and the real data is an argument
add_num1(10,20)

4. Function return value function

def buy():
    return 'smoke'

# Use variables to save the return value of the function
b = buy()
print(b)      #smoke

5. Application: calculate the sum of any two numbers and save the results

def sum_num(a,b):
    return a+b

result = sum_num(1,3)
print(result)

6. Documentation for functions

  • Definition function description document

def function name (parameter):

"" "location of documentation" ""

Code

  • View function description document

Help (function name)

7. Nested calls to functions

Nested function call means that another function is called in one function.

8. Variable scope

Variable scope refers to the effective range of variables, which is mainly divided into two categories: local variables and global variables.

  • Local variable: only takes effect inside the function body

Function of local variables: temporarily save data inside the function body, that is, when the function call is completed, destroy the local variables.

  • Global variable: a variable that can take effect both inside and outside a function

Modify global variables inside the function body: declare with the global keyword.

9. Parameters of function

  • Positional parameters: when calling a function, parameters are passed according to the parameter positions defined by the function.
# Location parameters
def user_info(name,age,gender):
    print("What's your name%s,Age is%s,Gender is%s" %(name,age,gender))

user_info('Tom',20,'male')

Note: the order and number of parameters passed and defined must be consistent.

  • Keyword parameters
def user_info(name,age,gender):
    print("What's your name%s,Age is%s,Gender is%s" %(name,age,gender))

#Keyword parameters
user_info('Rose',age=20,gender='female')
user_info(gender='female',age=20,name='Lily')

Writing method: key = value

Note: when calling a function, if there is a position parameter, the position parameter must be in front of the sub keyword parameter, but there is no order between the keyword parameters.

  • Default function: also known as default parameter. It is used to define parameters and provide default values for parameters. The value of the default parameter may not be passed when calling a function.
def user_info(name,age,gender='male'):
    print("What's your name%s,Age is%s,Gender is%s" %(name,age,gender))

#Default function
user_info('Tom',20)
user_info('Rose',18,'female')

Note: when calling a function, if it is the default parameter, modify the default parameter value; Otherwise, use this default value

  • Variable length function: variable parameter. It is used in scenarios where it is uncertain how many parameters will be passed during the call (it is OK not to pass parameters). At this time, it is very convenient to transfer the parameters by using the packaging location parameter or the package keyword parameter.
    • Package location transfer: collect all location parameters and return a tuple
    • Package keyword delivery: collect all keyword parameters and return a dictionary
#Indefinite length parameter
#Package location transfer
def user_info(*args):
    print(args)
user_info('Tom')            #('Tom',)
user_info('Tom',18)         #('Tom', 18)


#Package keyword delivery
def user_info(**kwargs):
    print(kwargs)
    
#{'gender': 'male', 'age': 20, 'name': 'Tom'}
user_info(name='Tom',age=20,gender='male')

10. Unpacking

#Unpacking element group
def return_num():
    return 100,200

num1,num2 = return_num()
print(num1)            #100
print(num2)            #200

#Unpacking dictionary
dict1 = {'name':'Tom','age':20}
a,b = dict1

# Unpack the dictionary and take out the key
print(a)               #name
print(b)               #age

print(dict1[a])        #Tom
print(dict1[b])        #20

 

11. Quote

In python, values are passed by reference.

We can use id() to determine whether two variables are the same and worthy of reference. The value of id can be understood as the identification of memory address.

a = 1
b = a
print(b)         #1

print(id(a))     #1716474656
print(id(b))     #1716474656

2, Application: college management system

1. System introduction: enter the system requirements and display the system function interface. The functions are as follows:

  • Add student
  • Delete student
  • Modify student information
  • Query student information
  • Display all student information
  • Exit the system
import time

def function():
    print("---" *4)
    print("1.Add student")
    print("2.Delete student")
    print("3.Modify student information")
    print("4.Query student information")
    print("5.Display all student information")
    print("6.Exit the system")
    print("---" *4)


students = []               #Student list

def add_student():
    """  
    Add student information 
    id:Student number
    name: full name
    sex: Gender
    """

    id = input("Please enter the student number of the student you want to add :")
    name = input("Please enter the name of the student you want to add :")
    sex = input("Please enter the gender of the student you want to add :")

    global students             #Declare global variables

    #Judge whether the student number exists
    for student in students:
        if name == student["name"]:
            print("The user already exists")
            add_student()

    # Add user data to dictionary
    student_dict = {}
    student_dict['id'] = id
    student_dict['name'] = name
    student_dict['sex'] = sex

    students.append(student_dict)

    print("id: %s,name: %s,sex: %s,Added successfully!" %(id,name,sex))

    time.sleep(1)           #Wait 1 second
    student_management()


def del_student():
    """ Delete student information """
    global students

    print(students)
    s = input("Please enter the name of the student to be deleted :")

               #Declare global variables

    #Determine whether the student exists
    i = 0
    for student in students:

        if s == student['name']:
            del students[i]
            print("delete%s success" %s)
            break
        i += 1

    else:
        print("No one is found...")


    student_management()

def alter_student():
    """ Modify student information """
    s = input("Please enter the name of the student to be modified")

    global students

    # Does the student exist
    for student in students:
        if s == student['name']:
            print("id:%s,name:%s,sex:%s" %(student['id'],student['name'],student['sex']))
            new_id = input("Please enter the modified student serial number :")
            new_name = input("Please enter the modified student name :")
            new_sex = input("Please enter the modified student gender :")

            student['id'] = new_id
            student['name'] = new_name
            student['sex'] = new_sex

            print("The modified data is id:%s,name:%s,sex:%s" % (student['id'], student['name'], student['sex']))
            time.sleep(1)


    else:
        print("The student does not exist, please re-enter!")

    student_management()



def selectid_student():
    """ Query student information """
    in_student = input("Please enter the name of the student to query!")

    global students

    #Determine whether the student exists
    for student in students:
        if student['name']  ==  in_student:
            print(student)
            student_management()
    else:
        print("The student cannot be queried...")
        selectid_student()




def select_student():
    """ Display all student information """
    for s in students:
        for key,value in s.items():
            print(("%s : %s")%(key,value),end="     ")
        print()
    student_management()




def student_management():
    """
    Function selected according to serial number
    """
    function()
    number = int(input("Please enter the function you want to enter:"))
    if number == 1:
        add_student()
    elif number == 2:
        del_student()
    elif number == 3:
        alter_student()
    elif number == 4:
        selectid_student()
    elif number == 5:
        select_student()
    else:
        q = input("Are you sure you want to exit,yes or no")
        if q == 'yes':
            quit()

3, Recursion

1. Characteristics of recursion

  • The function calls itself internally
  • There must be an exit
# Cumulative sum within 6

def sum_numbers(num):

    # If it is 1, return 1 directly
    if num == 1:
        return 1

    # If it is not 1, repeat the accumulation

    result = num + sum_numbers(num-1)

    return result

sum_number = sum_numbers(6)

print(sum_number)

4, lambda expression

Syntax: lambda argument list: expressions

Note:

  • The parameters of lambda expression are optional, and the parameters of function are fully applicable in lambda expression.
  • lambda function can accept any number of parameters, but can only return the value of one expression.
#function
def fn1():
    return 200

print(fn1)        #<function fn1 at 0x00000199C9D67F28>
print(fn1())      #200

#lambda expression
fn2 = lambda :100
print(fn2)        #<function <lambda> at 0x00000199CA077950>
print(fn2())      #100

#Print the lambda expression directly and output the memory address of the lambda

Application: calculate a+b

#Application a+b
#Function implementation
def add(a,b):
    return a+b
result = add(1,3)
print(result)            #4


#lambda implementation
print((lambda a,b : a+b)(1,6))     #7

2. Parameter form of lambda

  • No parameters
print((lambda:100)())                     #100
  • One parameter
print((lambda a:a)('hello world'))        #hello world
  • Default parameters
print((lambda a,b,c=100 :a+b+c)(10,40))   #150
  • Variable parameter: * * args
print((lambda *args:args)(10,20,30))      #(10,20,30)

After the variable parameters here are passed into lambda, the return value is tuple

  • Variable parameters: * * kwargs
print((lambda **kwargs:kwargs)(name="python",age=20))     #{'age': 20, 'name': 'python'}

3. Application of lambda

  • lambda with judgment
# lambda with judgment
print((lambda a,b:a if a > b else b)(1000,500))  #100
  • The list data is sorted by dictionary key value
#List data dictionary key value sorting

students = [
    {'name':'Tom','age':20},
    {'name':'Rose','age':19},
    {'name':'Lily','age':21},
    {'name':'Jack','age':23}
]

#Sort by name value in ascending order
students.sort(key=lambda x:x['name'])
#[{'name': 'Jack', 'age': 23}, {'name': 'Lily', 'age': 21}, {'name': 'Rose', 'age': 19}, {'name': 'Tom', 'age': 20}]
print(students)

#Sort by name value in descending order
students.sort(key=lambda x:x['name'],reverse=True)
# [{'name': 'Tom', 'age': 20}, {'name': 'Rose', 'age': 19}, {'name': 'Lily', 'age': 21}, {'name': 'Jack', 'age': 23}]
print(students)

# Sort in ascending order by age value
students.sort(key=lambda x:x['age'])
#[{'name': 'Rose', 'age': 19}, {'name': 'Tom', 'age': 20}, {'name': 'Lily', 'age': 21}, {'name': 'Jack', 'age': 23}]
print(students)

5, Higher order function

Pass the function as an argument

# Requirement: a function is used to calculate the sum of absolute values of any two numbers
#In python, the function abs() can calculate the absolute value
# Method 1
def add_num(a,b):
    return abs(a) + abs(b)

result = add_num(-1,2)
print(result)


#Method 2
def sum_num(a,b,f):
    return f(a)+f(b)

result = sum_num(-4,8,abs)
print(result)

1. Built in higher order function

  • map()
#map(func,lst), apply the passed function variable func to the American function of lst variable, and form a new iterator to return the result
# Requirement: calculate the power 2 of each number in list1 sequence
list1 = [1,2,3,4,5]

def func(x):
    return x ** 2

result = map(func,list1)
print(result)              #<map object at 0x000001410D0DD9E8>
print(list(result))        #[1, 4, 9, 16, 25]
  • reduce()
#reduce(func(x,y),lst), where func must have two parameters. The result of each func calculation continues to accumulate with the next element of the sequence.
#Requirement: calculate the cumulative sum of all numbers in list1 sequence
import functools

list1 = [1,2,3,5,7,9]

def sum(a,b):
    return a+b

result = functools.reduce(sum,list1)
print(result)            #25
  • filter()
#The filter(func,lst) function is used to filter the sequence, filter out the elements that do not meet the conditions, and return a filter object. If you need to convert it to a list, use list()

list1 = [1,2,3,4,5,6,7,8,9,10]

def func(x):
    return  x%2 == 0

result = filter(func,list1)
print(result)            #<filter object at 0x00000267A882DCF8>
print(list(result))      #[2, 4, 6, 8, 10]

6, Closure

python functions support nesting. If you reference variables in the scope of an external function (non global scope) in an internal function, the internal function will be called a closure.

Closures need to meet the following three conditions.

  1. Exists in two nested functions, and the closure is an internal function.
  2. The internal function refers to the variable (free variable) of the external function.
  3. The external function returns the function name of the internal function.
# External function
def outer(start = 0):
    count = [start]             #Variables within functions
    # Internal function
    def inner():
        count[0] += 1           #Variables that reference external functions
        return count[0]
    # Returns the name of the inner function
    return inner

out = outer(5)
print(out())                    #6

7, Decorator

Assuming that we have developed an existing function, we may add temporary requirements later, such as inserting logs. We can add a package function to take charge of these additional requirements. This package function is the decorator.

Main application scenarios of decorator:

  • Import log
  • Cleanup function after function execution
  • Function execution time statistics
  • Permission verification
  • Preparation before function execution
  • cache

Decorator is a function that needs to accept a parameter that represents the modified function.

By adding @ match and decorator name in front of the function definition, the decorator can wrap the function.

def wrap(func):
    print("Decorating")
    def inner():
        print("Verifying permissions")
        func()
    return inner

@wrap
def f1():
    print("f1")

f1()

Multiple decorators are applied to a function, and the call order is from bottom to top.

 

 

 

 

 

 

 

Topics: Python