Python實現購物小程序


一、需求

1、登錄
    {
    ‘xxx1’:{'passwd':'123','role':1,'moeny':10000,"carts":['mac']},
    'xxx1':{'passwd':'123','role':2,'moeny':10000,"carts":[]}
    }
    #role是1的話,代表管理員,2代表普通用戶
2、普通用戶:
    #查看所有的商品
    #輸入商品名稱添加到購物車,減去對應余額
    #可以查看自己購物車和余額,你已經買了xx東西,你還xxx錢
    #退出
3、管理員:
       #添加商品,商品名稱,商品價格
       #充值,輸入用戶名,給他加錢
       #退出                

 

二、全局變量和函數定義

USER_FILE全局變量,保存用戶信息
GOODS_FILE全局變量,保存商品信息
rw_file()讀寫文件
isprice()判斷輸入金額是否合法
login()用戶登錄:
    buyer()普通用戶登錄:
        find()查找所有商品
        buy()購買商品
        get()查詢購物車和余額
        exit()退出
    admin()管理員登錄:
        addgoods()添加商品
        recharge()充值
        exit()退出

 

三、實現代碼

USER_FILE = 'users.txt'
GOODS_FILE = 'goods.txt'


def rw_file(filename, content=0): #讀和寫文件
    if content:  #若content不為空,則判定為寫文件
        with open(filename,'w') as f:
            f.write(str(content))
    else:  #若content為空,則判定為讀文件
        with open(filename,'r') as f:
            f = eval(f.read())
            return f


def buyer(username):
    menu = {
        '1': find,
        '2': buy,
        '3': get,
        '4': exit
    }
    while True:
        choice = input("請輸入你想執行的操作(輸入【1】查看所有商品,輸入【2】添加商品,輸入【3】查詢購物車和余額,輸入【4】退出): ")
        if choice not in menu:
            print('輸入錯誤,請重新輸入')
        else:
            menu[choice](username)


def admin():
    menu = {
        '1': addgoods,
        '2': recharge,
        '3': exit
    }  # role為1時,為管理員
    while True:
        choice = input('請輸入你想執行的操作(輸入【1】添加商品,輸入【2】充值,輸入【3】退出): ')
        if choice not in menu:
            print('輸入錯誤,請重新輸入')
        else:
            menu[choice]()


def login(): #定義用戶登錄函數,根據用戶角色提供指定操作
    users = rw_file(USER_FILE)
    for i in range(3):
        username = input("請輸入賬號: ")
        passwd = input("請輸入密碼: ")
        if username in users and passwd == users[username]['passwd'] :
            if users[username]['role'] == '2': #如果role為2,則為普通用戶
                print('歡迎光臨')
                buyer(username)
            else:
                print('您已管理員身份登錄')
                admin( )
        else:
            print('賬號或密碼錯誤,還能嘗試%d次'%(2-i))
            i += 1


def find(*args): #普通查看所有商品
        with open('goods.txt') as f:
            print('所有商品和價格列表: ', f.read())


def buy(username): #普通用戶添加商品到購物車
    users = rw_file(USER_FILE)
    goods_all = rw_file(GOODS_FILE)
    goods = input('請輸入你要添加的商品: ')
    if goods in goods_all:
        if goods not in users[username]['carts']:
            if users[username]['money'] >= goods_all[goods]:
                users[username]['carts'].append(goods)
                users[username]['money'] =float('%.2f'%(users[username]['money'] - goods_all[goods]))
                with open('users.txt','w') as f2:
                    f2.write(str(users))
                    print('商品已成功添加到購物車')
            else:
                print('您的余額不足,請充值')
        else:
            print('購物車中已添加該商品,無需重復添加')
    else:
        print('您輸入的商品不存在')


def get(username): #普通用戶查詢購物車中的商品和余額
    users = rw_file(USER_FILE)
    if len(users[username]['carts']) > 0:
        print('您的購物車中已有商品:{goods}'.format(goods = users[username]['carts']))
    else:
        print('您還未添加任何商品')
    print('您的余額:{money}'.format(money=users[username]['money']))


def addgoods( ): #管理員添加商品
    goods_all = rw_file(GOODS_FILE)
    goods_name = input('請輸入商品名稱: ')
    goods_price = input('請輸入商品價格: ')
    if len(goods_name.strip()) != 0:
        if goods_name not in goods_all:
            if isprice(goods_price):
                goods_all[goods_name] = float('%.2f'%float(goods_price))
                rw_file(GOODS_FILE,goods_all)
                print('商品添加成功')
            else:
                print('商品價格必須是正數,請重新輸入')
        else:
            print('該商品已存在,無需重復添加')
    else:
        print('商品名稱不能為空,請重新輸入')


def recharge(): #管理員給指定賬號充值
    users = rw_file(USER_FILE)
    username = input('請輸入要充值的賬號: ')
    money = input('請輸入要添加的金額: ')
    if username in users and isprice(money):
        users[username]['money'] = float('%.2f'%(users[username]['money'] + float(money)))
        rw_file(USER_FILE, users)
        print('操作成功')
    else:
        print('輸入賬號或金額有誤,請重新輸入')


def isprice(price): #判斷金額是否有效
    if price.count('.') == 1 and price.split('.')[0].isdigit() and price.split('.')[1].isdigit():
        return True
    elif price.count('.') == 0 and price.isdigit():
        return True
    else:
        return False

login()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM