线上订餐系统初步python

本文介绍了作者使用Python制作的一个简单线上订餐系统,系统目前未使用数据库,数据安全性有待提升。文章提及,如果要修改菜单内容或增加菜单列表,需要对多个函数进行相应调整,适合初级Python学习者理解。
摘要由CSDN通过智能技术生成

介绍

今天心血来潮,就做了一个简单的线上订餐系统。有些不完善的地方,还请各位大佬多多包容。这里没有用到数据库,所以数据安全性还有待考究

import json
import time
import os
#open vip information
with open("foodShop_VipData.json", "r") as f:
    data = json.load(f)

# all the dishes
S = [["salad", 2.5], ["bread", 0.5], ["soup", 1.5]]  # small bug:length of S,M,D must be the same
M = [["beef", 10.0], ["pork", 6.0], ["chicken", 7.5]]
D = [["cake", 2.0], ["fruit", 1.0],["cookies",0.5]]
purchase = []


def Purchase(menu_choice):
    lst = []
    while True:
        choice = input("what do you want to buy(enter \"none\" to exit):")
        if menu_choice == "starter" and choice in list(dict(S).keys()):
            lst.append([choice, dict(S)[choice]])
            print(f"{choice} ordered!\n")

        elif menu_choice == "main" and choice in list(dict(M).keys()):
            lst.append([choice, dict(M)[choice]])
            print(f"{choice} ordered!\n")

        elif menu_choice == "dessert" and choice in list(dict(D).keys()):
            lst.append([choice, dict(D)[choice]])
            print(f"{choice} ordered!\n")
        
        elif choice == "none":
            print("")
            return lst
            
        else:
            print(f"we don't have {choice} in {menu_choice}, sorry!")


def SubMenu(lst,name):
    cnt=1
    print(f"\n{name} menu is:\n********************")
    print("name\tprice")
    for i in lst:
        print(f"{cnt}.{i[0]}\t{i[1]}pounds")
        cnt+=1
    print("********************")


def ShowMenu():
    print("\nwelcome to Jimmy's shop")
    print("********************")
    print("1.starter\n2.main\n3.dessert\n4.exit")
    print("********************")

    #vip set and purchase system
    while True:
        option = input("choose menu:starter/main/dessert:")
        time.sleep(0.5)
        if option == "1" or option == "starter":
            SubMenu(S,"starter")
            purchase.append(Purchase("starter"))

        elif option == "2" or option == "main":
            SubMenu(M, "main")
            purchase.append(Purchase("main"))

        elif option == "3" or option == "dessert":
            SubMenu(D, "dessert")
            purchase.append(Purchase("dessert"))

        elif option == "exit" or option == "4":
            print("")
            return purchase  

        else:
            print("invalid input\n")


def AUT():  # authentication
    print("remember, you can enter \"exit\" to leave this page")
    cnt = 0
    while True:
        cnt += 1
        name = input("enter your username:")
        password = input("enter your password:")
        if name == "exit" or password == "exit":
            return [False, 0]

        elif cnt >= 3:#limit log in times:3
            print("you have logged in for too many times!")
            return [False, 0]

        #searching username and password in json document
        for i in range(len(data)):
            if name == data[i][0] and password == data[i][1]:
                return [True, name]
        print("user name or password incorrect\n")


def Register():  # how to become a vip
    name = input("enter your user name:")
    while True:
        password = input("enter your password:")
        if len(password)<4:
            print("password too short, length should be above 3")
        else:
            break
    deposit = input("enter how much to store( must be over 50 pounds):")

    if deposit.isdigit():
        deposit = int(deposit)
        if deposit >= 50:#when the amount is greater than quota
            data.append([name, password, deposit])
            with open("foodShop_VipData.json", "w") as f1:
                json.dump(data, f1)
            print("register successful!\n")
            time.sleep(0.5)
            return True

        else:
            print("deposit should be above 50!")
            return False
    else:
        print("invalid input!")
        return False

#
def PayBill(isVIP, List, username=""):  # is ordered and
    if List == [[[]]]:  # not ordered
        decision=input("you have not ordered anything yet!\ndo you want to order now?:")
        if decision=="yes":
            return 1 #continue
        else:
            return 2#exit to main page

    else:  #payment section
        Sum=ShowOrder(List)
        if isVIP == True:
            orderList=Modi(List,True,username)
            Sum=ShowOrder(orderList)
            variable = SubroutineVIP(data, username, Sum)
            return 0

        else:
            orderList=Modi(List,False,money)
            Sum=ShowOrder(orderList)
            Subroutine(money, Sum)
            return 0

#modify orderList information
def Modi(orderList,isVIP,username="",money=0):
    accu=0
    print("add items/delete items/ready to pay")
    choice = input("enter your choice:")

    if choice == "add items":
        print("enter \"done\" when you ready")
        while True:
            item = input("enter the name of dish:")
            if item=="done":#out of  loop if finished
                print("")
                break

            for foodLst in [S,M,D]:#search if item is in S, M or D
                accu+=FindItem(foodLst,item)#get the price of item
            if accu==0:
                print(f"sorry, we don't have {item}")
            else:#append the items to the order list and then do some output
                orderList[0].append([item,accu])

    elif choice == "delete items":
        isIn=False
        print("enter \"done\" when you ready")
        while True:
            itemDelete = input("enter the name of dish to delete:")
            if itemDelete=="done":
                print("")
                break

            for sublst in orderList:
                for info in sublst:
                    if itemDelete in info:
                        sublst.remove(info)
                        isIn=True
            if isIn==False:
                print(f"you didn't order {item}")

    elif choice == "ready to pay":
        pass

    else:
        print("invalid input")

    return orderList


def FindItem(category,item):#finds if item is in a multidimentional list and returns the price
    for i in category:
        for j in i:
            if item in j:
                return j[1]#returns the price of the item
    return 0#when the item is not in the list


def ShowOrder(orderList):
    Sum=0
    cnt = 1
    print("you have ordered:")

    for i in orderList:
        for j in i:
            print(cnt, ".", j[0])
            Sum += j[1]
            cnt += 1

    print(f"{Sum} pounds in total\n")
    time.sleep(0.5)
    return Sum#the total cost of this meal

#vip payment method
def SubroutineVIP(data, username, moneyRequired):  # direct pay first
    for b in data:
        # deposit is greater than cost
        if username in b:
            if moneyRequired <= b[2]:
                b[2] -= moneyRequired#the money left in account

            else:
                print("sorry, you don't have enough money!")
                print("1.charge money\n2.check balance\n3.cancel order")
                choice=input("enter your choice:")

                if choice=="1" or choice=="charge money":
                    dif=moneyRequired-b[2]
                    while True:
                        amount=int(input(f"you need at least {dif}pounds:"))
                        if amount<dif:
                            print(amount,"pounds is not enough,still need ",dif-amount,"pounds")
                        else:
                            break

                    for info in data:
                        if username in info:
                            info[2]=amount-dif

                elif choice=="3" or choice=="cancel order":#when no enough money in account and not replenish
                    print("bill cancelled")
                    os._exit(0)
                
                elif choice=="2" or choice=="check balance":
                    CheckBalance(username)

                else:
                    print("invalid input")

    with open("foodShop_VipData.json", "w") as f2:
        json.dump(data, f2)
    print("the payment is successful!\n")
    return 0  # future adds the name of dishes and interact with other computer or devices


def CheckBalance(username):
    for info in data:
        if username in info:
            print(f"your balance is:{info[2]} pounds")
            return 0


def Subroutine(moneyRequired):
    moneyPaid = int(input("enter the money to pay:"))
    if moneyRequired <= moneyPaid:
        print("the paymentis successful!")
        print("return {} pounds back\n".format(moneyPaid-moneyRequired))
    else:
        print("the money is not enough\n")  # later comes up with repay


def Main():
    while True:
        print(
            "********************\n1.VIP channel\n2.normal channel\n3.become a VIP\n4.exit")
        print("********************")
        choice = input("enter your choice:")
        time.sleep(0.5)

        if choice == "1" or choice == "VIP channel":
            #authentication
            result = AUT()
            if result[0] == False:
                print("log in next time!\n")
            else:
                #discounts for VIPs
                temp = 0
                discount = 0.8
                for p1, p2, p3 in zip(S, M, D):
                    S[temp][1] = round(p1[1]*discount, 1)
                    M[temp][1] = round(p2[1]*discount, 1)
                    D[temp][1] = round(p3[1]*discount, 1)
                    temp += 1

                while True:
                    List = ShowMenu()#costumer order food
                    number=PayBill(True, List, result[1])#result[1] is username
                    if number!=1:
                        break

        elif choice == "2" or choice == "normal channel":
            #entailing reorder function
            while True:
                List = ShowMenu()#costumer order food
                number=PayBill(False, List)
                if number!=1:
                    break

        elif choice == "3" or choice == "become a VIP":
            boolean = Register()
            while boolean == False:
                option2 = input("register again or not(enter yes or no):")
                if option2 == "yes":
                    boolean = Register()
                elif option2 == "no":
                    break
                else:
                    print("invalid input")

        elif choice == "4" or choice == "exit":
            print("see you next time")
            time.sleep(1)
            os._exit(0)
        else:
            print("invalid input\n")
            time.sleep(0.5)

Main()

修改S,M,D里面的元素数量对程序的运行时毫无影响的,如果您想修改S,M,D三个列表里面装的元素类别(比如从”主食“换到“小吃”),您可能就要小费一番周折了:您需要修改ShowMenu()和Purchase()函数中的一些内容。

但是如果您想修改列表数量,比如从S,M,D三个列表,变成S,M,D,R,那您就要修改这段代码的很多地方,比如Main()函数里面的“VIP channel” if语句,你就要在循环中加多R以对该列表中所有内嵌列表中的第二个元素值也就是食物价格进行修改。另外,您还需要在Purchase()和ShowMenu()函数中新增if判断。

除了代码量以外,这段代码还是不难的,涉及的python知识也比较初级,几乎所有学python的朋友都能看懂这个代码和逻辑。

 

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值