Python 模擬購物車的實例講解
1.功能簡介
此程序模擬用戶登陸商城后購買商品操作??蓪崿F(xiàn)用戶登陸、商品購買、歷史消費記查詢、余額和消費信息更新等功能。首次登陸輸入初始賬戶資金,后續(xù)登陸則從文件獲取上次消費后的余額,每次購買商品后會扣除相應(yīng)金額并更新余額信息,退出時也會將余額和消費記錄更新到文件以備后續(xù)查詢。
2.實現(xiàn)方法
架構(gòu):
本程序采用python語言編寫,將各項任務(wù)進行分解并定義對應(yīng)的函數(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ù)字鍵選擇相應(yīng)選項進行操作。
(2)任意時刻按q鍵退出退出登陸,退出前會完成用戶消費和余額信息更新。
使用文件:
(1)userlist.txt
存放用戶賬戶信息文件,包括用戶名、密碼、登陸次數(shù)和余額。每次用戶登陸成功會更新該用戶登陸次數(shù),每次按q鍵退出時會更新余額信息。
(2)***_cost_record.txt
存放某用戶***消費記錄的文件,用戶首次購買商品后創(chuàng)建,沒有購買過商品的用戶不會產(chǎn)生該文件。每次按q鍵退出時會將最新的消費記錄更新到文件。
3.流程圖

4.代碼
# Author:Byron Li
#-*-coding:utf-8-*-
'''----------------------------------------------使用文件說明----------------------------------------------------------
使用文件說明
userlist.txt 存放用戶賬戶信息文件,包括用戶名、密碼、登陸次數(shù)和余額
***_cost_record.txt 存放某用戶***消費記錄的文件,用戶首次購買商品后創(chuàng)建,沒有購買過商品的用戶不會產(chǎn)生該文件
---------------------------------------------------------------------------------------------------------------------'''
import os
import datetime
def 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 None
def 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 False
def 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 False
def 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 False
def 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 False
def 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)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Pytorch如何指定device(cuda or cpu)
這篇文章主要介紹了Pytorch如何指定device(cuda or cpu)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
Python 實現(xiàn)「食行生鮮」簽到領(lǐng)積分功能
今天我們就用 Python 來實現(xiàn)自動簽到,省得我每天打開 APP 來操作了。感興趣的朋友跟隨小編一起看看吧2018-09-09

