Business card management system--python entry project

statement

This project is aimed at getting started with python. This project is the integration of all the basic knowledge of python. The content may be a bit cumbersome, and the explanation is relatively detailed. I hope you can read it carefully, and then type it again to consolidate the foundation

function display

Main interface
insert image description here
Query all business cards
insert image description here
, modify and delete
insert image description here

Preparation before development

Because the system has many functions, it would be ugly to display it in one file. Here we use multiple files to display, and use the method of calling files to realize the system functions. Here I created two python files, one is cards_main.py mainly as a file showing the system and functions, and the other is cards_tool.py as a tool file for the main file

System framework construction

When developing this project, the first thing we have to do is to write the framework of the program. Only after the framework is built can it be ready for our later development functions. First of all, we first determine the functions of the business card management system:
when we enter the system, the system will let us enter the operation we want to perform, here we use numbers instead:
when we input 1, the system will allow us to add a business card;
when we input 2, The system will display all business cards;
when entering 3, the system will display the query business card;
when entering 0, the system will exit the system.
After the execution, the system will return to the main interface, allowing the user to re-enter. Later, we will add functions such as business card deletion and business card modification.
Here we first look at the general framework of the business card management system:
the following picture is the file of cards_main.py

# cards_main.py

# 导入cards_tool文件
import cards_tool
# while True 会不停循环,除非输入0,break退出循环
while True:
	# 导入cards_tool.py 文件里的show_menu功能
    cards_tool.show_menu()
	
    action_str = input('请选择希望执行的操作:')

    print("您选择的操作是【%s】" % action_str)

    # 如果在开发程序时,不希望立刻编写内部分支结构的代码,可以用pass
    # 1,2,3 争对名片的操作
    if action_str in ['1', '2', '3']:
        
        # 新增名片
        if action_str == '1':
            cards_tool.new_card()

        # 显示全部名片
        elif action_str == '2':
            cards_tool.show_all()

        # 查询名片
        elif action_str == '3':
            cards_tool.search_card()

    # 0 退出系统
    elif action_str == '0':

        print('欢迎再次使用【名片管理系统】')
        break

    # 其他内容输入错误,提示用户
    else:
        print("您输入的不正确,请重新选择")


Here, since we want the system to return to the main interface after each execution, we need to use the while loop, while True will keep looping, unless we enter break to exit the loop, which is exactly the effect we want, confirm the loop After that, we will use the nesting of if and elif to complete the matching of subsequent input numbers and functions.

The following figure is the file content of cards_tool.py
Create a function show_menu() to display the main page
Create a function new_card() to create a new business card
Create a function to display all business cards show_all()
Create a function to search for business cards search_card()

# cards_tool.py

# 主要作为显示系统主页面的功能
def show_menu():
    """显示菜单"""
    print('*' * 50)
    print('欢迎使用【名片管理系统】')
    print("")
    print("1. 新增名片")
    print("2. 显示全部")
    print("3. 搜索名片")
    print("")
    print("0. 退出系统")
    print('*' * 50)

# 新增名片
def new_card():
    """新增名片"""
    print('-' * 50)
    print("新增名片")


# 显示所有名片
def show_all():
    """显示所有名片"""
    print('-' * 50)
    print("显示所有名片")


# 搜索名片
def search_card():
    """搜索名片"""
    print('-' * 50)
    print("搜索名片")

The system framework is almost developed at this point, and then it will mainly focus on the development of functions, that is, it will mainly make a fuss in the cards_tool.py file to improve each function file.

Note:
1. Here I use the method of importing show_menu() in the cards_tool.py file to realize the function of displaying the main menu.
2. The method of importing the function in the file is the direct file name. The function is fine, for example: cards_tool.new_card()

Structure for saving business card data

To save the business card data, we can use a list to save the business card. We can use a dictionary to save the content of the business card. Later, we can directly use card_list to perform all operations. The following
figure is cards_tool.

# cards_tool.py
# 记录所有名片字典
card_list = []

Note: card_list[] must be defined at the top of the file, because python is an interpreted language and will interpret the code from top to bottom.

Add business card function

The figure below is the new_card() function in the cards_tool.py file

# 新增名片功能
def new_card():
    """新增名片"""
    print('-' * 50)
    print("新增名片")

    # 1. 提示用户输入名片的详细信息
    name_str = input('请输入姓名:')
    phone_str = input('请输入电话:')
    QQ_str = input('请输入QQ号码:')
    email_str = input('请输入邮箱地址')

    # 2.使用用户输入的信息建立一个名片字典
    card_dict = {
    
    "name": name_str,
                 "phone": phone_str,
                 "QQ": QQ_str,
                 "email": email_str}

    # 3.将名片字典添加到列表中
    card_list.append(card_dict)

    print(card_list)

    # 4.提示用户添加成功
    print("添加 %s 的名片成功!" % name_str)

After reading all the codes, let’s analyze the corresponding functions of the codes:
1. First store user information, we need to think of dictionary storage, and then use lists to store dictionaries. For this reason, we have created a card_list and card_dict
2. Prompt the user to enter a business card For detailed information, use input() to solve
3. Use the information entered by the user to create a business card dictionary
4. Add the business card dictionary to the list
5. Finally, output the list directly to see the information you just entered

Show all card features

The figure below is the show_all() function in the cards_tool.py file

# 显示所有名片功能
def show_all():
    """显示所有名片"""
    print('-' * 50)
    print("显示所有名片")

    # 判断是否存在名片记录,如果没有,提示用户并返回
    if len(card_list) == 0:
        print("当前没有任何的名片记录,请使用新增功能添加名片!")
        
        # return下方的代码不会被执行
        # 如果return 后面没有任何内容,就会返回到调用函数的位置
        return

    # 打印表头
    for name in ["姓名", "电话", "QQ", "邮箱"]:
        # 让输出更美观可以用类似表格的形式输出,用end="" 使name输出后不换行
        # \t的作用是为了让表头之间增加两个制表符的距离,更美观
        print(name, end="\t\t")

    # 这个print是作为换行的作用,换行后输出结果
    print('')

    # 打印分割线
    print("=" * 70)

This function is more complicated, let's explain it step by step:
1. When there is no data in the business card list, output "Currently there is no business card record, please use the new function to add business card!", and will not output the following print header content, this time we need to use return, return can not only be used as a return value, if there is no return value, it will directly jump to the position where the function is defined, and the most important thing: python will not execute the code behind return .

2. In order to make the output business card more beautiful, the form of the output result can be converted into a table format. The function of end="" is to keep the four headers of name, phone, QQ, and email in a straight line without line breaks.\ t is the distance of one tab, you can use the distance of two tabs, which is more beautiful.

3. print("") is to change the line, so that the output result is below the header.

Query business card function

The figure below is the show_all() function in the cards_tool.py file

# 搜索名片功能
def search_card():
    """搜索名片"""
    print('-' * 50)
    print("搜索名片")

    # 1.提示用户输入要搜索的姓名
    find_name = input("请输入要搜索的姓名:")

    # 2.遍历名片列表,查询要搜索的姓名,如果没有找到,需要提示用户
    for card_dict in card_list:
        if card_dict["name"] == find_name:

            print("姓名\t\t电话\t\tQQ\t\t邮箱")
            print('=' * 60)
            print("%s\t\t%s\t\t%s\t\t%s" % (card_dict["name"],
                                            card_dict["phone"],
                                            card_dict["QQ"],
                                            card_dict["email"]))

            break

    else:
        print("抱歉,没有找到 %s" % find_name)

Searching business cards is relatively simple, that is, if the searched name is found, it will be output and the information will be output. The output format can refer to the function of displaying all business cards. If there is no name, it will output not found.

This is the end of the basic business card management system here. The following is mainly to improve the system, add, modify and delete functions

Delete and edit business cards

# 删除和修改名片
def deal_card(find_dict):

    print(find_dict)

    action_str = input("请选择要执行的操作 [1]:修改, [2]:删除, [0]:返回上级")

    if action_str == '1':

        find_dict["name"] = input_card_info(find_dict["name"], "姓名:")
        find_dict["phone"] = input_card_info(find_dict["phone"], "电话:")
        find_dict["QQ"] = input_card_info(find_dict["QQ"], "QQ:")
        find_dict["email"] = input_card_info(find_dict["email"], "邮箱:")
        print("修改名片成功")

    elif action_str == '2':

        card_list.remove(find_dict)
        print("删除名片成功")


def input_card_info(dict_value, tip_message):

    # 1.提示用户输入内容
    result_str = input(tip_message)

    # 2.针对用户的输入内容进行判断,如果用户输入了内容,直接返回结果
    if len(result_str) > 0:
        return result_str

    # 3.如果用户没有输入内容,返回字典中原有的值
    else:
        return dict_value

To delete and modify a business card, I am based on querying the business card. First of all, we first determine the detailed functions of modifying and deleting the business card: 1. After
we query the business card, we can delete the entire business card.
2. After querying the business card, we can modify the value we want Modify, if you don’t want to modify, take the original value directly

After determining the function, we will now complete the above function

1. Because it is based on the query function, we insert a function in the query function, and then define the function.
Note: Here you can use it in a function first and then define it outside the function.
insert image description here
Here we first pass it to the function that we want to modify. Or delete the dictionary, and then accept and modify it in the deal_card() function

2. Let's execute the delete function first. Deletion is relatively simple. If we choose to delete, we can directly use the remove() function to delete

3. For the modification function, what we describe is that you can modify the value you want to modify. If you don’t want to modify it, you can directly take the original value,
so you must not directly use input() to input it. This will cause the content you don’t want to modify to have to be given again It assigns a value. So now we should think: if I don't input, it will directly accept the value in the original dictionary, if I input it, it will accept the input value.
Here we create a new function input_card_info() mainly to judge whether we have input value The two formal parameters inside, one is dict_value, which is mainly to return the original value when we have no input content, and the other tip_message is mainly to remind us of the current input, such as name, QQ. Finally, we directly bring the input_card_info() function into the deal_card() function for judgment.

code display

cards_main.py file

# cards_main.py

# 导入cards_tool文件
import cards_tool
# while True 会不停循环,除非输入0,break退出循环
while True:

    # 导入cards_tool.py 文件里的show_menu功能
    cards_tool.show_menu()

    action_str = input('请选择希望执行的操作:')

    print("您选择的操作是【%s】" % action_str)

    # 如果在开发程序时,不希望立刻编写内部分支结构的代码,可以用pass
    # 1,2,3 争对名片的操作
    if action_str in ['1', '2', '3']:

        # 新增名片
        if action_str == '1':
            cards_tool.new_card()

        # 显示全部名片
        elif action_str == '2':
            cards_tool.show_all()

        # 查询名片
        elif action_str == '3':
            cards_tool.search_card()

    # 0 退出系统
    elif action_str == '0':

        print('欢迎再次使用【名片管理系统】')
        break

    # 其他内容输入错误,提示用户
    else:
        print("您输入的不正确,请重新选择")

cards_tool.py file

# cards_tool.py
# 记录所有名片字典
card_list = []


# 主要作为显示系统主页面的功能
def show_menu():
    """显示菜单"""
    print('*' * 50)
    print('欢迎使用【名片管理系统】')
    print("")
    print("1. 新增名片")
    print("2. 显示全部")
    print("3. 搜索名片")
    print("")
    print("0. 退出系统")
    print('*' * 50)


# 新增名片功能
def new_card():
    """新增名片"""
    print('-' * 50)
    print("新增名片")

    # 1. 提示用户输入名片的详细信息
    name_str = input('请输入姓名:')
    phone_str = input('请输入电话:')
    QQ_str = input('请输入QQ号码:')
    email_str = input('请输入邮箱地址')

    # 2.使用用户输入的信息建立一个名片字典
    card_dict = {
    
    "name": name_str,
                 "phone": phone_str,
                 "QQ": QQ_str,
                 "email": email_str}

    # 3.将名片字典添加到列表中
    card_list.append(card_dict)

    print(card_list)

    # 4.提示用户添加成功
    print("添加 %s 的名片成功!" % name_str)


# 显示所有名片功能
def show_all():
    """显示所有名片"""
    print('-' * 50)
    print("显示所有名片")

    # 判断是否存在名片记录,如果没有,提示用户并返回
    if len(card_list) == 0:
        print("当前没有任何的名片记录,请使用新增功能添加名片!")

        # return下方的代码不会被执行
        # 如果return 后面没有任何内容,就会返回到调用函数的位置
        return

    # 打印表头
    for name in ["姓名", "电话", "QQ", "邮箱"]:
        # 让输出更美观可以用类似表格的形式输出,用end="" 使name输出后不换行
        # \t的作用是为了让表头之间增加两个制表符的距离,更美观
        print(name, end="\t\t")

    # 这个print是作为换行的作用,换行后输出结果
    print('')

    # 打印分割线
    print("=" * 70)

    # 遍历名片列表依次输出字典信息
    for card_dict in card_list:

        print("%s\t\t%s\t\t%s\t\t%s" % (card_dict["name"],
                                        card_dict["phone"],
                                        card_dict["QQ"],
                                        card_dict["email"]))


# 搜索名片功能
def search_card():
    """搜索名片"""
    print('-' * 50)
    print("搜索名片")

    # 1.提示用户输入要搜索的姓名
    find_name = input("请输入要搜索的姓名:")

    # 2.遍历名片列表,查询要搜索的姓名,如果没有找到,需要提示用户
    for card_dict in card_list:
        if card_dict["name"] == find_name:

            print("姓名\t\t电话\t\tQQ\t\t邮箱")
            print('=' * 60)
            print("%s\t\t%s\t\t%s\t\t%s" % (card_dict["name"],
                                            card_dict["phone"],
                                            card_dict["QQ"],
                                            card_dict["email"]))

            deal_card(card_dict)

            break

    else:
        print("抱歉,没有找到 %s" % find_name)


# 删除和修改名片
def deal_card(find_dict):

    print(find_dict)

    action_str = input("请选择要执行的操作 [1]:修改, [2]:删除, [0]:返回上级")

    if action_str == '1':

        find_dict["name"] = input_card_info(find_dict["name"], "姓名:")
        find_dict["phone"] = input_card_info(find_dict["phone"], "电话:")
        find_dict["QQ"] = input_card_info(find_dict["QQ"], "QQ:")
        find_dict["email"] = input_card_info(find_dict["email"], "邮箱:")
        print("修改名片成功")

    elif action_str == '2':

        card_list.remove(find_dict)
        print("删除名片成功")


def input_card_info(dict_value, tip_message):

    # 1.提示用户输入内容
    result_str = input(tip_message)

    # 2.针对用户的输入内容进行判断,如果用户输入了内容,直接返回结果
    if len(result_str) > 0:
        return result_str

    # 3.如果用户没有输入内容,返回字典中原有的值
    else:
        return dict_value

Summarize

The business card management system is almost completed here. These functions may not be perfect, and there may be some bugs. I hope that you can understand the meaning of these functions and variables and understand their functions when you tap bit by bit. After mastering, you can add new functions to it.

Guess you like

Origin blog.csdn.net/m0_64041302/article/details/127871019