• 作业: 小型购物系统---按函数模式编写


    作业:
     用户入口:
     1. 商品信息存在文件里
     2. 已够商品,余额记录
     
     商家入口
     2. 可以添加商品,修改商品价格

    import os, sys, copy,time
    products_db = "simple_shop_system_products.db"
    cart_db = "simple_shop_system_carts.db"

    # get product data from database
    def read_products_from_db(database_name):
    if os.path.exists(database_name):
    with open(database_name,"r") as fs:
    return (True, fs.read())
    else:
    return (False, "Products database not exist !")

    # write product data into database
    def write_products_to_db(database_name, product_data):
    if os.path.exists(database_name):
    with open(database_name, "w") as fs:
    fs.write(product_data)
    fs.flush()
    return (True, "Save Successfully")
    else:
    return (False, "Product's database not exist !")

    # show system info and entrance to user
    def show_system_info():
    print("*" * 60)
    print("*%s*" % " ".center(58))
    print("*%s*" % "Shopping System".center(58))
    print("*%s*" % "v1.00".center(58))
    print("*%s*" % "1.For Host user 2.For Customer user".center(58))
    print("*%s*" % " ".center(58))
    print("*" * 60)

    def show_error(error_inio):
    print("Error:%s" % error_inio)

    def show_pass(pass_info):
    print("Pass:%s" % pass_info)

    # check format for input data:
    def input_and_check(right_data, prompt_data, flag_type):
    # flag is True for string else for number
    while True:
    data = input(prompt_data).strip()
    if not data:
    show_error("Input is Null!")
    continue
    if flag_type == False:
    if data.isdigit():
    data = int(data)
    else:
    show_error("Input error!")
    continue
    if len(right_data) > 0:
    if not data in right_data:
    show_error("Input error!")
    continue
    else:
    return data
    else:
    return data

    def show_products_list(product_data, title_info):
    print("*" * 60)
    print("|| %s" % title_info)
    print("-" * 60)
    print("|{name}|{price}|{balance}|".format(name="Name".center(25, " "), price="Price".center(15, " "), balance="Balance".center(16, " ")))
    print("-" * 60)
    for n in product_data:
    # print(n, product_data[n]["price"], product_data[n]["stocks"])
    print("|{name}|{price}|{balance}|".format(name=n.center(25, " "), price=str(product_data[n]["price"]).center(15, " "), balance=str(product_data[n]["stocks"]).center(16, " ")))
    print("-" * 60)

    def host_user_func():
    # get data from database;
    data = read_products_from_db(products_db)
    if data[0] == True:
    product_data = eval(data[1])
    else:
    sys.exit("Error:%s"% data[1])
    while True:
    show_products_list(product_data, "Products List: ")
    print("*" * 60)
    print("*%s*" % " 1. Edit Price".ljust(58, " "))
    print("*%s*" % " 2. Add Product".ljust(58, " "))
    print("*%s*" % " 3. Remove Products".ljust(58, " "))
    print("*%s*" % " 4. Back To Home".ljust(58, " "))
    print("*%s*" % " 5. Exit System".ljust(58, " "))
    print("*" * 60)
    select_data = input_and_check((1, 2, 3, 4, 5), "Please select: ", False)

    # for change product price
    if select_data == 1:
    product_selected = input_and_check(product_data, "Select Products: ", True)
    product_info = {product_selected: copy.deepcopy(product_data[product_selected])}
    show_products_list(product_info, "Product Selected:")
    new_price = input_and_check((), "Input New Price: ", False)
    product_info[product_selected]["price"] = new_price
    show_products_list(product_info, "Product Changed:")
    product_confirm = input_and_check(("Y", "N"), "Please Confirm (Y/N): ", True)
    if product_confirm == "Y":
    product_data[product_selected] = product_info[product_selected]
    show_pass("the %s's price changed Successfully!" % product_selected)
    else:
    show_error("the %s's price changed Fail!" % product_selected)
    print("=" * 60)
    print()

    # for add new products
    elif select_data == 2:
    new_product = input_and_check((), "New Product's Name: ", True)
    new_price = input_and_check((), "New Product's Price:", False)
    new_stocks = input_and_check((), "New Product's Stocks: ", False)
    product_info = {new_product: {'price': new_price, 'stocks': new_stocks}}
    show_products_list(product_info, "New Products:")
    product_confirm = input_and_check(("Y", "N"), "Please Confirm (Y/N): ", True)
    if product_confirm == "Y":
    if new_product in product_data:
    product_info[new_product]["stocks"] += product_data[new_product]["stocks"]
    product_data[new_product] = product_info[new_product]
    show_pass("the %s' Create Successfully!" % new_product)
    else:
    show_error("the %s Create changed Fail!" % new_product)
    print("=" * 60)

    # for products delete
    elif select_data == 3:
    product_delete = input_and_check(product_data, "Select Products: ", True)
    product_info = {product_delete: product_data[product_delete]}
    show_products_list(product_info, "Product Selected:")
    product_confirm = input_and_check(("Y", "N"), "Please Confirm (Y/N): ", True)
    if product_confirm == "Y":
    del product_data[product_delete]
    show_pass("the %s'Remove Successfully!" % product_delete)
    else:
    show_error("the %s Remove Fail!" % product_delete)
    print("=" * 60)

    # for back to home page
    elif select_data == 4:
    confirm_data = input_and_check(("Y", "N"), "Save Data ? (Y/N):", True)
    if confirm_data.upper() == "Y":
    write_status = write_products_to_db(products_db, str(product_data))
    if write_status[0] == True:
    print(write_status[1])
    break
    else:
    sys.exit(write_status[1])
    else:
    break

    # for System exiting ...
    else:
    confirm_data = input_and_check(("Y", "N"), "Save Data ? (Y/N):", True)
    if confirm_data.upper() == "Y":
    write_status = write_products_to_db(products_db, str(product_data))
    if write_status[0] == True:
    print(write_status[1])
    sys.exit("System exiting....")
    else:
    sys.exit(write_status[1])
    else:
    sys.exit("System exiting....")

    def customer_user_func():
    # get data from database;
    data1 = read_products_from_db(products_db)
    if data1[0] == True:
    product_data = eval(data1[1])
    else:
    sys.exit("Error:%s"% data1[1])

    # get data from carts
    data2 = read_products_from_db(cart_db)
    if data2[0] == True:
    cart_data = eval(data2[1])
    else:
    sys.exit("Error:%s"% data2[1])

    while True:
    show_products_list(product_data, "Products List: ")
    product_selected = input_and_check(product_data, "Select Product: ", True)
    cart_data.append(product_selected)
    show_pass("Add %s into cart successfully !" % product_selected)
    print("*" * 60)
    print("*%s*" % "1.Continue 2.Charge 3. Exit System".center(58, " "))
    print("*" * 60)
    select_action = input_and_check((1, 2, 3), "Select : ", False)
    if select_action == 1:
    continue;
    elif select_action == 2:
    cart_info = list(set(cart_data))
    print("")
    print("*" * 60)
    print("|%s|" % "Products List In Cart".center(58, " "))
    print("-" * 60)
    print("|{id}|{name}|{price}|{quantity}|{total}|".format(id="ID".center(5, " "), name="Name".center(19, " "),
    price="Price".center(10, " "), quantity="Quantity".center(10, " "), total="Total".center(10, " ")))
    print("-" * 60)
    total_price = 0
    for c_id, c_name in enumerate(cart_info):
    print("|{id}|{name}|{price}|{quantity}|{total}|".format(id=str(c_id).center(5, " "), name=c_name.center(19, " "),
    price=str(product_data[c_name]["price"]).center(10, " "), quantity=str(cart_data.count(c_name)).center(10, " "),
    total=str(product_data[c_name]["price"] * cart_data.count(c_name)).center(10, " ")))
    print("-" * 60)
    total_price += product_data[c_name]["price"] * cart_data.count(c_name)
    print("|{data_name}|{date_value}|{total_name}|{total_value}|".format(data_name="Date".center(10, " "),date_value=str(time.strftime('%Y-%m-%d',time.localtime())).center(15, " "),
    total_name="Total".center(10, " "), total_value=str(total_price).center(20," ")))
    print("-" * 60)
    print()
    print("*" * 60)
    print("*%s*" % "1.Back to Menu 2.Pay Account".center(58, " "))
    print("*" * 60)
    select_action = input_and_check((1, 2), "Select : ", False)
    if select_action == 1:
    continue;
    else:
    confirm_data = input_and_check(("Y", "N"), "Confirm Payment ?(Y/N):", True)
    if confirm_data == "Y":
    cart_data.clear()
    write_status = write_products_to_db(cart_db, str(cart_data))
    show_pass("Pay for successfully !")
    break
    else:
    show_error( "Pay for Fail!")
    continue;
    else:
    confirm_data = input_and_check(("Y", "N"), "Save Cart ? (Y/N):", True)
    if confirm_data == "Y":
    write_status = write_products_to_db(cart_db, str(cart_data))
    if write_status[0] == True:
    sys.exit(write_status[1])
    else:
    sys.exit(write_status[1])
    else:
    sys.exit("System exit....")
    def main():
    while True:
    show_system_info()
    sel_data = input_and_check((1, 2),"please select:", False)
    # if sel_data = 1 for Host User, else for customer user;
    if sel_data == 1:
    host_user_func();
    else:
    customer_user_func();
    if __name__ == "__main__":
    main()
  • 相关阅读:
    快乐来源的研究
    这可能是经历中真实的农村
    golang入门到实战教程
    免费开源pdf阅读器SumatraPDF
    农村题材光棍儿
    在线头像卡通化
    微软出品电脑管家
    刚毕业的大学生、失业的父亲:父子返乡
    ApplicationEventPublisher的简单使用
    mysql里使用JSON_EXTRACT取值
  • 原文地址:https://www.cnblogs.com/brace2011/p/9191622.html
Copyright © 2020-2023  润新知