python模拟购物车购物过程_Python 模拟购物车的实例讲解
1.功能簡介
此程序模擬用戶登陸商城后購買商品操作。可實現用戶登陸、商品購買、歷史消費記查詢、余額和消費信息更新等功能。首次登陸輸入初始賬戶資金,后續登陸則從文件獲取上次消費后的余額,每次購買商品后會扣除相應金額并更新余額信息,退出時也會將余額和消費記錄更新到文件以備后續查詢。
2.實現方法
架構:
本程序采用python語言編寫,將各項任務進行分解并定義對應的函數來處理,從而使程序結構清晰明了。主要編寫了六個函數:
(1)login(name,password)
用戶登陸函數,實現用戶名和密碼驗證,登陸成功則返回登陸次數。
(2)get_balance(name)
獲取用戶余額數據。
(3)update_balance(name,balance)
更新用戶余額數據,當用戶按q鍵退出時數據會更新到文件。
(4)inquire_cost_record(name)
查詢用戶歷史消費記錄。
(5)update_cost_record(name,shopping_list)
更新用戶消費記錄,當用戶按q鍵退出時本次消費記錄會更新到文件。
(6)shopping_chart()
主函數,完成人機交互,函數調用,各項功能的有序實現。
主要操作:
(1)根據提示按數字鍵選擇相應選項進行操作。
(2)任意時刻按q鍵退出退出登陸,退出前會完成用戶消費和余額信息更新。
使用文件:
(1)userlist.txt
存放用戶賬戶信息文件,包括用戶名、密碼、登陸次數和余額。每次用戶登陸成功會更新該用戶登陸次數,每次按q鍵退出時會更新余額信息。
(2)***_cost_record.txt
存放某用戶***消費記錄的文件,用戶首次購買商品后創建,沒有購買過商品的用戶不會產生該文件。每次按q鍵退出時會將最新的消費記錄更新到文件。
3.流程圖
4.代碼
# Author:Byron Li
#-*-coding:utf-8-*-
'''----------------------------------------------使用文件說明----------------------------------------------------------
使用文件說明
userlist.txt 存放用戶賬戶信息文件,包括用戶名、密碼、登陸次數和余額
***_cost_record.txt 存放某用戶***消費記錄的文件,用戶首次購買商品后創建,沒有購買過商品的用戶不會產生該文件
---------------------------------------------------------------------------------------------------------------------'''
import os
import datetime
def login(name,password): #用戶登陸,用戶名和密碼驗證,登陸成功則返回登陸次數
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): #獲取用戶余額數據
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): #更新用戶余額數據
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'])): #第一次創建時第一行標上“商品 價格”
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,'-')) #寫入消費時間信息方便后續查詢
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(): #主函數,用戶交互,函數調用,結果輸出
product_list=[
('Iphone',5000),
('自行車',600),
('聯想電腦',7800),
('襯衫',350),
('洗衣機',1000),
('礦泉水',3),
('手表',12000)
] #商店商品列表
shopping_list=[] #用戶本次購買商品列表
while(True):
username = input("請輸入用戶名:")
password = input("請輸入密碼:")
login_times=login(username,password) #查詢輸入用戶名和密碼是否正確,正確則返回登陸次數
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)
if int(product_list[int(choice)][1])
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 模擬購物車的實例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持。
總結
以上是生活随笔為你收集整理的python模拟购物车购物过程_Python 模拟购物车的实例讲解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: power automate deskt
- 下一篇: 3GP格式转换为AMV格式