Home > Backend Development > Python Tutorial > How to write a simple library management system using Python?

How to write a simple library management system using Python?

WBOY
Release: 2023-05-07 21:52:10
forward
3123 people have browsed it

    Development steps

    1. Enter the prompt:

    In order to create a friendly "library management system", first list all Function menu. As follows:

    print("""
    ***************************
    * 欢迎进入图书管理系统    *
    * 0 .退出                 *
    * 1 .列出所有书籍         *
    * 2 .添加书籍             *
    * 3 .修改书籍             *
    * 4 .删除书籍             *
    * 5 .借书                 *
    * 6 .还书                 *
    ***************************
    """)
    Copy after login

    2. Obtain user input:

    In the second step, the user will enter an integer from 0 to 6 to correspond to the relative function. If the user makes an input error, "Input error, please re-enter" is output.

    while True:
        n=input("输入序号(0-6):")
        if n=="0":
            pass
        elif n=="1":
            pass
        elif n=="2":
            pass
        elif n=="3":
            pass
        elif n=="4":
            pass
        elif n=="5":
            pass
        elif n=="6":
            pass
        else:
            print("输入错误,请重新输入")
            print("")   #表示换一行
    Copy after login

    Extension:

    Many languages ​​provide "empty statement" support. Python is no exception. Python’s pass statement is an empty statement.

    Sometimes the program needs to occupy a space and put a statement, but does not want this statement to do anything. In this case, it can be achieved through the pass statement. By using the pass statement, you can make your program more complete.

    The following program demonstrates the use of pass as an empty statement:

    s=int(input("请输入一个整数: "))
    if s>5:
        print("大于5")
    elif s<5:
        pass   # 相当于占位符
    else:
        print("等于5")
    Copy after login

    As you can see from the above program, for the case where s is less than 5, the program will not process it temporarily. (or don't know how to deal with it), at this time the program needs to occupy a position through an empty statement, so that the pass statement can be used.

    3. Improve each command program

    For example: if the user inputs "0", it not only needs to tell the user that "the program has exited", but also To complete the "exit" function, the code is as follows:

    if n=="0":
        print("退出成功")
        break
    Copy after login

    Another example: the user enters "5" (borrowing a book). If there is still inventory, it prompts "Borrowing successfully" and decreases This book is in stock. Otherwise it will prompt "Insufficient Stock". The following program:

    elif n=="5":
        xh=intinput()
        book=books[xh-1]
        if book["num"]>0:
            book["num"]-=1
            print("借书成功")
        else:
            print("库存不足")
    Copy after login

    Please refer to the above code to improve other functions.

    4. Optimize the program to make the code more concise

    You can define functions and recycle functions, which contributes to the simplicity of the code. For example, code:

    def intinput(n="请输入序号:"):
        while True:
            s=input(n)
            if s.isnumeric():
                return int(s)
            else:
                print("请输入整数")
    Copy after login

    Extension:

    str.isnumeric() Method:

    Detects whether the string consists only of numbers. This method is only for unicode objects.

    Function parameter meanings and precautions:

    The meaning of each part of the parameters is as follows:

    • Function name: In fact, it is a Identifiers that conform to Python syntax, but readers are not recommended to use simple identifiers such as a, b, c as function names. The function name should best reflect the function of the function (such as my_len above, which means our custom len() function).

    • Formal parameter list: Set how many parameters the function can receive. Multiple parameters are separated by commas (,).

    • [return [return value]]: The whole function is used as an optional parameter to set the return value of the function. In other words, a function can use a return value or no return value. Whether it is needed depends on the actual situation.

    Note: When creating a function, even if the function does not require parameters, a pair of empty "()" must be retained, otherwise the Python interpreter will prompt an "invaild syntax" error. Alternatively, if you want to define an empty function without any functionality, you can use the pass statement as a placeholder.

    Advantages of functions:

    • The biggest and most intuitive advantage of using functions in python is that you can encapsulate a piece of code so that it can be called at any time, which can greatly It improves the simplicity and readability of the program, and also makes the logic of the code clearer.

    • Generally speaking, code blocks encapsulated by functions are used to implement a certain function, and code encapsulated into functions can be called repeatedly. This can not only improve the development efficiency of python programs, but also reduce the writing of unnecessary code.

    • Another advantage of the function is that it is actually a module independent of other external codes. If you do not call the function manually when a python program is executed, then this function will not To execute. When an error occurs in a function, it can be easily modified without causing too much impact on the running of the program, and modularization is well achieved.

    • The python function can also be directly saved in a py file and then imported as a module. In this way, a universally written python function can be used in many different programs. , the commonly used built-in modules and python third-party libraries actually store functions one by one.

    All codes of the library management system:

    def intinput(n="请输入序号:"):
        while True:
            s=input(n)
            if s.isnumeric():
                return int(s)
            else:
                print("请输入整数")
     
    books=[{"name":"Scratch","isbn":"12345","num":2},
           {"name":"Python","isbn":"12346","num":5}]
    print("""
    ***************************
    * 欢迎进入图书管理系统    *
    * 0 .退出                 *
    * 1 .列出所有书籍         *
    * 2 .添加书籍             *
    * 3 .修改书籍             *
    * 4 .删除书籍             *
    * 5 .借书                 *
    * 6 .还书                 *
    ***************************
    """)
     
    while True:
        n=input("输入序号(0-6):")
        if n=="0":
            print("退出成功")
            break
        elif n=="1":
            print("序号\t书名\t书号\t数量")
            index=1
            for book in books:
                print("%d\t%s\t%s\t%d"%(index,book["name"],book["isbn"],book["num"]))
                index+=1
        elif n=="2":
            book=dict()
            book["name"]=input("请输入书名:")
            book["isbn"]=input("请输入书号:")
            book["num"]=intinput("请输入数量:")      
            books.append(book)
            print("添加成功")
        elif n=="3":
            try:
                xh=intinput()
                book=books[xh-1]
                book["name"]=input("请输入书名:")
                book["isbn"]=input("请输入书号:")
                book["num"]=intinput("请输入数量:")
                print("修改成功")
            except:
                print("出错了")
        elif n=="4":
            s=intinput()
            if 1<=s<=len(books):
                del books[xh-1]
                print("删除成功")
            else:
                print("超出范围")
        elif n=="5":
            xh=intinput()
            book=books[xh-1]
            if book["num"]>0:
                book["num"]-=1
                print("借书成功")
            else:
                print("库存不足")
        elif n=="6":
            xh=intinput()
            try:
                book=books[xh-1]
                book["num"]-=1
                print("还书成功")
            except:
                print("未查询到书本")
        else:
            print("输入错误,请重新输入")
            print("")
    Copy after login

    The above is the detailed content of How to write a simple library management system using Python?. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template