国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python 模擬購物車的實例講解

2020-01-04 16:43:03
字體:
供稿:網(wǎng)友

1.功能簡介

此程序模擬用戶登陸商城后購買商品操作。可實現(xiàn)用戶登陸、商品購買、歷史消費記查詢、余額和消費信息更新等功能。首次登陸輸入初始賬戶資金,后續(xù)登陸則從文件獲取上次消費后的余額,每次購買商品后會扣除相應金額并更新余額信息,退出時也會將余額和消費記錄更新到文件以備后續(xù)查詢。

2.實現(xiàn)方法

架構(gòu):

本程序采用python語言編寫,將各項任務進行分解并定義對應的函數(shù)來處理,從而使程序結(jié)構(gòu)清晰明了。主要編寫了六個函數(shù):

(1)login(name,password)

用戶登陸函數(shù),實現(xiàn)用戶名和密碼驗證,登陸成功則返回登陸次數(shù)。

(2)get_balance(name)

獲取用戶余額數(shù)據(jù)。

(3)update_balance(name,balance)

更新用戶余額數(shù)據(jù),當用戶按q鍵退出時數(shù)據(jù)會更新到文件。

(4)inquire_cost_record(name)

查詢用戶歷史消費記錄。

(5)update_cost_record(name,shopping_list)

更新用戶消費記錄,當用戶按q鍵退出時本次消費記錄會更新到文件。

(6)shopping_chart()

主函數(shù),完成人機交互,函數(shù)調(diào)用,各項功能的有序?qū)崿F(xiàn)。

主要操作:

(1)根據(jù)提示按數(shù)字鍵選擇相應選項進行操作。

(2)任意時刻按q鍵退出退出登陸,退出前會完成用戶消費和余額信息更新。

使用文件:

(1)userlist.txt

存放用戶賬戶信息文件,包括用戶名、密碼、登陸次數(shù)和余額。每次用戶登陸成功會更新該用戶登陸次數(shù),每次按q鍵退出時會更新余額信息。

(2)***_cost_record.txt

存放某用戶***消費記錄的文件,用戶首次購買商品后創(chuàng)建,沒有購買過商品的用戶不會產(chǎn)生該文件。每次按q鍵退出時會將最新的消費記錄更新到文件。

3.流程圖

Python,購物車

4.代碼

# Author:Byron Li#-*-coding:utf-8-*-'''----------------------------------------------使用文件說明----------------------------------------------------------使用文件說明userlist.txt     存放用戶賬戶信息文件,包括用戶名、密碼、登陸次數(shù)和余額***_cost_record.txt 存放某用戶***消費記錄的文件,用戶首次購買商品后創(chuàng)建,沒有購買過商品的用戶不會產(chǎn)生該文件---------------------------------------------------------------------------------------------------------------------'''import osimport datetimedef login(name,password):  #用戶登陸,用戶名和密碼驗證,登陸成功則返回登陸次數(shù)  with open('userlist.txt', 'r+',encoding='UTF-8') as f:    line = f.readline()    while(line):      pos=f.tell()      line=f.readline()      if [name,password] == line.split()[0:2]:        times=int(line.split()[2])        line=line.replace(str(times).center(5,' '),str(times+1).center(5,' '))        f.seek(pos)        f.write(line)        return times+1  return Nonedef get_balance(name):  #獲取用戶余額數(shù)據(jù)  with open('userlist.txt', 'r',encoding='UTF-8') as f:    line = f.readline()    for line in f:      if name == line.split()[0]:        return line.split()[3]  print("用戶%s不存在,無法獲取其余額信息!"%name)  return Falsedef update_balance(name,balance):  #更新用戶余額數(shù)據(jù)  with open('userlist.txt', 'r+',encoding='UTF-8') as f:    line = f.readline()    while(line):      pos1=f.tell()      line=f.readline()      if name == line.split()[0]:        pos1=pos1+line.find(line.split()[2].center(5,' '))+5        pos2=f.tell()        f.seek(pos1)        f.write(str(balance).rjust(pos2-pos1-2,' '))        return True  print("用戶%s不存在,無法更新其余額信息!" % name)  return Falsedef inquire_cost_record(name):   #查詢用戶歷史消費記錄  if os.path.isfile(''.join([name,'_cost_record.txt'])):    with open(''.join([name,'_cost_record.txt']), 'r',encoding='UTF-8') as f:      print("歷史消費記錄".center(40, '='))      print(f.read())      print("".center(46, '='))      return True  else:    print("您還沒有任何歷史消費記錄!")    return Falsedef update_cost_record(name,shopping_list):  #更新用戶消費記錄  if len(shopping_list)>0:    if not os.path.isfile(''.join([name, '_cost_record.txt'])):   #第一次創(chuàng)建時第一行標上“商品 價格”      with open(''.join([name, '_cost_record.txt']), 'a',encoding='UTF-8') as f:        f.write("%-5s%+20s/n" % ('商品', '價格'))        f.write(''.join([datetime.datetime.now().strftime('%c'), ' 消費記錄']).center(40,'-'))  #寫入消費時間信息方便后續(xù)查詢        f.write('/n')        for product in shopping_list:          f.write("%-5s%+20s/n"%(product[0],str(product[1])))    else:      with open(''.join([name, '_cost_record.txt']), 'a',encoding='UTF-8') as f:        f.write(''.join([datetime.datetime.now().strftime('%c'), ' 消費記錄']).center(40, '-'))        f.write('/n')        for product in shopping_list:          f.write("%-5s%+20s/n"%(product[0],str(product[1])))    return True  else:    print("您本次沒有購買商品,不更新消費記錄!")    return Falsedef shopping_chart():  #主函數(shù),用戶交互,函數(shù)調(diào)用,結(jié)果輸出  product_list=[    ('Iphone',5000),    ('自行車',600),    ('聯(lián)想電腦',7800),    ('襯衫',350),    ('洗衣機',1000),    ('礦泉水',3),    ('手表',12000)  ]  #商店商品列表  shopping_list=[]  #用戶本次購買商品列表  while(True):    username = input("請輸入用戶名:")    password = input("請輸入密碼:")    login_times=login(username,password)  #查詢輸入用戶名和密碼是否正確,正確則返回登陸次數(shù)    if login_times:      print('歡迎%s第%d次登陸!'.center(50,'*')%(username,login_times))      if login_times==1:        balance = input("請輸入工資:")  #第一次登陸輸入賬戶資金        while(True):          if balance.isdigit():            balance=int(balance)            break          else:            balance = input("輸入工資有誤,請重新輸入:")      else:        balance=int(get_balance(username)) #非第一次登陸從文件獲取賬戶余額      while(True):        print("請選擇您要查詢消費記錄還是購買商品:")        print("[0] 查詢消費記錄")        print("[1] 購買商品")        choice=input(">>>")        if choice.isdigit():          if int(choice)==0:         #查詢歷史消費記錄            inquire_cost_record(username)          elif int(choice)==1:        #購買商品            while (True):              for index,item in enumerate(product_list):                print(index,item)              choice=input("請輸入商品編號購買商品:")              if choice.isdigit():                if int(choice)>=0 and int(choice)<len(product_list):                  if int(product_list[int(choice)][1])<balance:  #檢查余額是否充足,充足則商品購買成功                    shopping_list.append(product_list[int(choice)])                    balance = balance - int(product_list[int(choice)][1])                    print("/033[31;1m%s/033[0m已加入購物車中,您的當前余額是/033[31;1m%s元/033[0m" %(product_list[int(choice)][0],balance))                  else:                    print("/033[41;1m您的余額只剩%s元,無法購買%s!/033[0m" %(balance,product_list[int(choice)][0]))                else:                  print("輸入編號錯誤,請重新輸入!")              elif choice=='q':   #退出賬號登陸,退出前打印本次購買清單和余額信息,并更新到文件                if len(shopping_list)>0:                  print("本次購買商品清單".center(50,'-'))                  for product in shopping_list:                    print("%-5s%+20s"%(product[0],str(product[1])))                  print("".center(50, '-'))                  print("您的余額:/033[31;1m%s元/033[0m"%balance)                  update_cost_record(username,shopping_list)                  update_balance(username, balance)                  print("退出登陸!".center(50, '*'))                  exit()                else:                  print("您本次沒有消費記錄,歡迎下次購買!")                  print("退出登陸!".center(50, '*'))                  exit()              else:                print("選項輸入錯誤,請重新輸入!")          else:            print("選項輸入錯誤,請重新輸入!")        elif choice=='q':  #退出賬號登陸          print("退出登陸!".center(50, '*'))          exit()        else:          print("選項輸入錯誤,請重新輸入!")      break    else:      print('用戶名或密碼錯誤,請重新輸入!')shopping_chart() #主程序運行

以上這篇Python 模擬購物車的實例講解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網(wǎng)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 临邑县| 健康| 南丹县| 同江市| 华蓥市| 海宁市| 佛教| 宁城县| 化德县| 吐鲁番市| 遵义市| 蓬安县| 漳浦县| 同德县| 灵璧县| 皋兰县| 民丰县| 静安区| 江陵县| 遵化市| 孙吴县| 荔波县| 江源县| 惠来县| 碌曲县| 北票市| 来安县| 贵溪市| 北京市| 彭阳县| 夏河县| 崇阳县| 长沙县| 泗阳县| 二连浩特市| 临沧市| 偃师市| 庆城县| 桐城市| 长武县| 宁河县|