Python learning notes-17

Function enhancement

Application: college management system

System introduction

Requirements: enter the system display system function interface, and the functions are as follows:

  1. Add student
  2. Delete student
  3. Modify student information
  4. Query student information
  5. Display all student information
  6. Exit the system
    The system has 6 functions, which users can select according to their own needs.

Step analysis

  1. Display function interface
  2. User input function serial number
  3. Execute different functions (functions) according to the function serial number entered by the user
    3.1 defining functions
    3.2 calling functions

Demand realization

Display function interface

Define function print_info, responsible for displaying system functions.

# Define function interface function
def print_info():
    print('-------Please select a function-------')
    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('-'*22)

Calling code:

# 1. Display function interface
print_info()

User input function serial number

# 2. User input function serial number
user_num = int(input('Please enter the function serial number'))

User input function of serial number

# 3. The function serial number entered by the user performs different functions (functions)
if user_num == 1:
    print('Add student')
elif user_num == 2:
    print('Delete student')
elif user_num == 3:
    print('Modify student information')
elif user_num == 4:
    print('Query student information')
elif user_num == 5:
    print('Display all student information')
elif user_num == 6:
    print('Exit the system')

Define functions for different functions

All function functions are operation school information. All information stored for all students should be a global variable with the data type of list.

info = []
  1. Add student

Demand analysis: receive and save the college information input by users; Judge whether to add student information (if the student name already exists, an error prompt will be reported; if the student name does not exist, prepare an empty dictionary, add the data entered by the user to the dictionary, and then add dictionary data to the list); Call this function where the corresponding if condition holds.

code implementation

# Add student
info = []
def add_info():
    '''Add student'''
    # Enter college information
    new_name = input('Please enter the student name:')
    new_id = input('Please enter student id: ')
    new_tel = input('Please enter the student telephone number:')

    # Judge the student information from the global variable info
    global info 
    for i in info:
        if new_name == i['name']:
            print('The user already exists!')
            return
    
    # If the name entered by the user does not exist, add the student information
    info_dict = {}

    # Append the data entered by the user to the dictionary
    info_dict['id'] = new_id
    info_dict['name'] = new_name
    info_dict['tel'] = new_tel

    # Append this student information dictionary to the list
    info.append(info_dict)

    print(info)
  1. Delete student
    Demand analysis: delete according to the student name entered by the user: enter the name of the target student; Check whether the student exists (if so, delete the data; if not, prompt "the user does not exist"); Call this function where the corresponding if condition holds.
    code implementation
# Delete student
def del_info():
    '''Delete student'''
    # 1. Enter the name of the student you want to delete
    del_name = input('Name of the student you want to delete:')

    # 2. Judge whether the name exists in the data in the global variable
    for i in info:
        if del_name == i['name']:
            info.remove(i)
            break

    else:
        print('The student does not exist')    
    print(info)
  1. Modify student information
    Demand analysis: enter the name of the target student; Check whether the student exists (if so, modify the student's information, such as mobile phone number; if not, report an error); Call this function where the corresponding if condition holds.
    code implementation
# Modify student information
def modify_info():
    '''Modify student information'''
    # 1. User input target student information
    modify_name = input('Please enter the name of the student who wants to modify the information:')

    # 2. In the global variable, check whether the student exists
    global info
    for i in info:
        if modify_name == i['name']:
            i['tel'] = input('Please enter a new phone number:')
            break
        else:
            print('The student does not exist!')
    print(info)
  1. Query student information
    Demand analysis: enter the name of the target student; Check whether the student exists (if so, the information of the student will be displayed; if not, an error will be reported)
    code implementation
# Query student information
def search_info():
    '''Query student information'''
    # 1. Enter the name of the student you want to query
    search_name = input('Please enter the name of the student you want to query:')

    # 2. In the global variable, check whether the student exists
    for i in info:
        if search_name == i['name']:
            print('The student information found is as follows:')
            print(f"The student's name is{i['name']},Student number is{i['id']},The phone number is{i['tel']}")
        else:
            print('The student does not exist!')
  1. Display all student information
    Demand analysis: print all student information
    code implementation
# Display all student information
def print_all():
    '''Display all student information'''
    print('Student number\t full name\t Mobile number')
    for i in info:
        print(f'{{i['id']}}\t{i['name']}\t{i['tel']}')
  1. Exit the system
    code implementation
    elif user_num == 6:
        exit_flag = input('Are you sure you want to exit? yes or no')
        if exit_flag == 'yes':
            break

All functions are implemented in code. Next, let's take a look at the full version of the code!

info = []
def print_info():
    print('-------Please select a function-------')
    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('-'*22)

# Add student
def add_info():
    '''Add student'''
    # Enter college information
    new_name = input('Please enter the student name:')
    new_id = input('Please enter student id: ')
    new_tel = input('Please enter the student telephone number:')

    # Judge the student information from the global variable info
    global info 
    for i in info:
        if new_name == i['name']:
            print('The user already exists!')
            return
    
    # If the name entered by the user does not exist, add the student information
    info_dict = {}

    # Append the data entered by the user to the dictionary
    info_dict['id'] = new_id
    info_dict['name'] = new_name
    info_dict['tel'] = new_tel

    # Append this student information dictionary to the list
    info.append(info_dict)

    print(info)

# Delete student
def del_info():
    '''Delete student'''
    # 1. Enter the name of the student you want to delete
    del_name = input('Name of the student you want to delete:')

    # 2. Judge whether the name exists in the data in the global variable
    for i in info:
        if del_name == i['name']:
            info.remove(i)
            break

    else:
        print('The student does not exist')    
    print(info)

# Modify student information
def modify_info():
    '''Modify student information'''
    # 1. User input target student information
    modify_name = input('Please enter the name of the student who wants to modify the information:')

    # 2. In the global variable, check whether the student exists
    global info
    for i in info:
        if modify_name == i['name']:
            i['tel'] = input('Please enter a new phone number:')
            break
        else:
            print('The student does not exist!')
    print(info)

# Query student information
def search_info():
    '''Query student information'''
    # 1. Enter the name of the student you want to query
    search_name = input('Please enter the name of the student you want to query:')

    # 2. In the global variable, check whether the student exists
    for i in info:
        if search_name == i['name']:
            print('The student information found is as follows:')
            print(f"The student's name is{i['name']},Student number is{i['id']},The phone number is{i['tel']}")
        else:
            print('The student does not exist!')

# Display all student information
def print_all():
    '''Display all student information'''
    print('Student number\t full name\t Mobile number')
    for i in info:
        print(f'{{i['id']}}\t{i['name']}\t{i['tel']}')

# The system needs to be recycled until it exits the system
while True:
    # 1. Display function interface
    print_info()

    # 2. User input function serial number
    user_num = int(input('Please enter the function serial number'))
 
    # 3. The function serial number entered by the user performs different functions (functions)
    if user_num == 1:
        print('Add student')
        add_info()
    elif user_num == 2:
        print('Delete student')
        del_info()
    elif user_num == 3:
        print('Modify student information')
        modify_info()
    elif user_num == 4:
        print('Query student information')
        search_info()
    elif user_num == 5:
        print('Display all student information')
        print_all()
    elif user_num == 6:
        exit_flag = input('Are you sure you want to exit? yes or no')
        if exit_flag == 'yes':
            break
    else:
        print('There is an error in the input function, please re-enter')

recursion

Recursive application scenarios

Recursion is a programming idea:

  1. In our daily development, if we traverse all the files under a folder, we usually use recursive implementation;
  2. In the subsequent algorithm class, many algorithms are inseparable from recursion. For example: quick sort.

Characteristics of recursion

The function calls itself internally
There must be an exit

Application: Digital summation within 3

code

# 3 + 2 + 1
def sum_num(num):
    # 1. If it is 1, directly return to 1 -- exit
    if num == 1:
        return 1
    # 2. If it is not 1, repeat the accumulation and return the result
    return num + sum_num(num-1)
result = sum_num(3)
print(result) # 6

results of enforcement

You can use the Debug tool to view

Recursive exit problem

Error code:

# 3 + 2 + 1
def sum_num(num):
    # 1. If it is 1, directly return to 1 -- exit
    # if num == 1:
    #     return 1
    # 2. If it is not 1, repeat the accumulation and return the result
    return num + sum_num(num-1)

result = sum_num(3)
print(result) # 6

Error reporting information

  File "c:\Users\Administrator\Desktop\1.py", line 9, in <module>
    result = sum_num(3)
  File "c:\Users\Administrator\Desktop\1.py", line 7, in sum_num
    return num + sum_num(num-1)
  File "c:\Users\Administrator\Desktop\1.py", line 7, in sum_num
    return num + sum_num(num-1)
  File "c:\Users\Administrator\Desktop\1.py", line 7, in sum_num
    return num + sum_num(num-1)
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded

Where 996 is the recursion depth.

lambda expression

Application scenario of lambda

If the function should have a return value and only one sentence of code, it can be simplified by using lanbda.

lambda syntax

lambda argument list: expressions

be careful
The parameters of lambda expression are optional, and the parameters of function are fully applicable in lambda expression.
lambda expressions can accept any number of parameters, but can only return the value of one expression.

quick get start

# function
def fn1():
    return 200 
print(fn1) # <function fn1 at 0x00000127864F3E20>
print(fn1()) # 200

# lambda expressions 
fn2 = lambda : 100
print(fn2) # <function <lambda> at 0x000001278661E830>
print(fn2()) # 100

Note: the lambda expression is allowed directly, and the memory address of the lambda is output.

Example: calculate a+b

Function implementation

def add(a,b):
    return a+b
result = add(1,2)
print(result) # 3
# Thinking: simple requirements, more code

lambda implementation

fn1 = lambda a,b : a+b
print(fn1(1,2)) # 3

Parameter form of lambda

No parameters

fn1 = lambda : 100
print(fn1()) # 100

One parameter

fn1 = lambda a : a
print('hallo world') # hallo world

Default parameters

fn1 = lambda a,b,c=100:a,b,c
print(fn1(10,20)) # 10,20,100

Variable parameter * args

fn1 = lambda *args: args
print(10,20,30) # (10,20,30)

Variable parameters * * kwargs

fn1 = lambda **kwargs : kwargs
print(fn1(name = 'txd',age = 18)) # {'name': 'txd', 'age': 18}

lambda application

lambda with judgment

fn1 = lambda a,b:a if a > b else b
print(fn1(1,2))

The list book is sorted by the value of the dictionary key

from curses import keyname


studens = [
    {'name':'txd','age':18},
    {'name':'yy','age':19},
    {'name':'ll','age':17}
]

# sort(key = lambda...,....)
# 1. Sort the values corresponding to name key in ascending order
studens.sort(key=lambda x:x['name'])
print(studens)
# 2. Sort the values corresponding to name key in descending order
studens.sort(key=lambda x:x['name'],reverse=True)
print(studens)
# 3. Sort the values corresponding to age key in ascending order
studens.sort(key=lambda x:x['age'])
print(studens)

Higher order function

Pass in functions as parameters. Such functions are called high-order functions. High-order functions are the embodiment of functional programming, which refers to this highly abstract programming paradigm.

Experience higher order function

In python, the abs() function can calculate the absolute value of numbers.

abs(-10) # 10

The round() function can complete the rounding calculation of numbers,

round(1.2) # 1
round(1.9) # 2

Demand: sum any two numbers after sorting them according to the specified requirements.
Method 1

def add_num(a,b):
    return abs(a) + abs(b)
result = add_num(-4,2)
print(result)  # 6

Method 2

def add_num(a,b,f):
    return f(a) + f(b)
result = add_num(-4,2,abs)
print(result)  # 6

Note: after comparing the two expressions, it is found that the code of method 2 will be more concise and the function flexibility will be higher.

Functional programming uses a lot of functions to reduce the repetition of code, so the program is relatively short and the development speed is fast.

Built in higher order function

map()

map(func,lst), apply the passed in function variable func to each element of the variable for two or three days, and form a new list of the results to return.
Requirement: calculate the power 2 of each number in list1 sequence.

lsit1 = [3,4,5]
def func(x):
    return x**2

result = map(func,lsit1)
print(result) # <map object at 0x0000021AB3CFE260>
print(list(result)) # [9, 16, 25]

reduce()

reduce(func,lst): func must have two parameters. The result of each func calculation will continue to accumulate with the next element of the sequence.

Note: the parameter func passed in by reduce() must receive 2 parameters.

Requirement: calculate the cumulative sum of all numbers in list1 sequence.

import functools
from unittest import result

list1 = [1,2,3,4,5]
def func(a,b):
    return a + b
result = functools.reduce(func,list1)
print(result) # 15

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 want to convert it to a list, you can use list() to convert

list1 = [1,2,3,4,5,6,7,8,9]
def func(x):
    return x %2 ==0

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

Tags: Python list

Posted by tony.j.jackson@o2.co.uk on Sat, 16 Apr 2022 02:54:40 +0930