Python 實現(xiàn)購物商城,含有用戶入口和商家入口的示例
這是模擬淘寶的一個簡易的購物商城程序。
用戶入口具有以下功能:
登錄認證
可以鎖定用戶
密碼輸入次數(shù)大于3次,鎖定用戶名
連續(xù)三次輸錯用戶名退出程序
可以選擇直接購買,也可以選擇加入購物車
用戶使用支付密碼完成支付,支付密碼連續(xù)輸入錯誤達3次,鎖定用戶名
商家入口具有以下功能:
登錄認證
可以鎖定用戶
密碼輸入次數(shù)大于3次,鎖定用戶名
連續(xù)三次輸錯用戶名退出程序
商家可以編輯商品
上架新品
下架商品
修改商品信息:商品名、單價、庫存
每個用戶的用戶名、密碼、余額、支付密碼,以行記錄定義在 user_list.txt 文件中,以逗號分隔;
每件商品的商品名、單價、庫存,以行記錄定義在 product_list.txt 文件中,以逗號加一個空格分隔;
被鎖定用戶名記錄在 lock_list.txt 文件中,以行分隔;
商家的用戶名、密碼定義在 seller_list.txt 文件中,以逗號分隔;
# Joe Young
import getpass
import os
# 調(diào)用os模塊的system方法傳入'cls'參數(shù),清屏
os.system('cls')
while True:
entrance = input('請選擇:\n\t1. 用戶登陸\n\t2. 商家登陸\n>>>')
if entrance != '1' and entrance != '2':
print('\n輸入有誤,請重試...\n')
else:
break
# 打印商品列表
def print_product_list():
index = 1
with open('product_list.txt', 'r') as product_file:
for product_line in product_file:
L = [commodity, price, stock] = product_line.strip('\n').split(', ')
commodity_list.append(L)
print((str(index) + '. ' + commodity).ljust(20) + ('單價:' + price + '元').ljust(15) + '庫存:' + stock)
index += 1
return
# 用戶入口
if entrance == '1':
info = [] # 存放用戶的信息,初始為空
if_payed = True # if_payed 表示訂單是否已支付
username = ''
# 登錄接口
count = 0
while count < 3:
username = input('\n用戶名: ')
# 打開鎖定列表文件
with open('lock_list.txt', 'r+') as lock_file:
for lock_line in lock_file:
# 用戶名在鎖定名單里面,則退出程序
if username == lock_line.strip('\n'):
exit('\n用戶名 %s 已被鎖定,請聯(lián)系管理員...' % username)
login = False # 登錄標志,初始為False
# 打開用戶名列表文件,讀權(quán)限
user_file = open('user_list.txt', 'r')
for user_line in user_file:
# 獲取每行的用戶信息,用戶名、密碼、余額、支付密碼,存入info列表
info = [user, passwd, balance, pay_passwd] = user_line.strip('\n').split(',')
# 用戶名匹配,則進入密碼輸入環(huán)節(jié)
if user == username:
n = 0
# 3次輸入機會
while n < 3:
password = getpass.getpass('密碼: ')
# 密碼匹配,顯示登錄成功
if passwd == password:
print('\n歡迎 %s 登錄商城,祝您購物愉快!\n' % username)
login = True # 登錄標志賦值為True
break
# 密碼不匹配
else:
# n = 2 時是最后一次機會,不必提示還剩下0次機會
if n != 2:
print('\n密碼錯誤,請重新輸入,您還有 %d 次機會\n' % (2-n))
n += 1
# 密碼錯誤次數(shù)達到3次,鎖定用戶名,退出程序
else:
open('lock_list.txt', 'w').write(username + '\n')
exit('\n錯誤次數(shù)過多,賬戶已被鎖定...')
# 登錄成功,跳出for循環(huán)
if login:
break
else:
if count != 2:
print('\n用戶名不存在,請重試,您還有 %d 次機會' % (2-count))
user_file.close()
count += 1
# 登錄成功,跳出while循環(huán)
if login:
break
else:
exit('\n錯誤次數(shù)過多,程序已退出...')
# 購買程序
shopping_cart = [] # 購物車初始為空
commodity_list = []
print_product_list()
while True:
i = input('\n請選擇商品(輸入序號),或輸入 c 取消購買:')
if i == 'c':
while True:
a = input('\n是否繼續(xù)購買?(Y/N):')
if a == 'n' or a == 'N':
exit('\n交易結(jié)束...')
elif a == 'y' or a == 'Y':
break
else:
print('\n輸入格式有誤,請重試...')
continue
if not i.isdigit():
print('\n輸入格式有誤,請重試...')
continue
i = int(i)
if i <= 0 or i > len(commodity_list):
print('\n此商品不存在,請重試...')
continue
item_name = commodity_list[i-1][0] # 商品名稱
item_price = commodity_list[i-1][1] # 商品價格
item_stock = commodity_list[i-1][2] # 商品庫存
print('\n您已選擇了 %s ,請輸入購買的數(shù)量,或輸入 b 重新選擇:' % item_name)
back = False
while True:
num = input('>>>')
if num == 'b':
back = True
break
if not num.isdigit():
print('輸入格式有誤,請重試...')
continue
if int(num) > int(item_stock):
print('數(shù)量大于庫存,請重試...')
continue
if int(num) == 0:
print('數(shù)量應(yīng)大于0,請重試...')
break
if back:
continue
item = [item_name, item_price, num]
print('\n您已選擇了 %s,單價:%s 元,數(shù)量:%s,您想立即購買還是加入購物車?\n' % (item_name, item_price, num))
print('\t1. 立即購買\n\t2. 加入購物車\n')
while True:
choice = input('>>>')
if not (choice == '1' or choice == '2'):
print('輸入有誤,請重試...')
continue
break
user_balance = int(info[2])
# 立即購買
if choice == '1':
amount = int(item_price) * int(num)
count = 0
cancel = False
while count < 3:
user_pay_passwd = getpass.getpass('\n請輸入支付密碼,或輸入 c 放棄支付:')
if user_pay_passwd == 'c':
print('\n取消支付成功...')
cancel = True
break
elif user_pay_passwd != info[3]:
if count != 2:
print('\n密碼錯誤,請重試,您還有 %d 次機會...' % (2-count))
count += 1
else:
break
if count == 3:
with open('lock_list.txt', 'w') as lock_file:
lock_file.write(username + '\n')
exit('密碼錯誤,賬戶已被鎖定...')
if cancel:
while True:
choice = input('\n是否繼續(xù)購買?(Y/N):')
if not (choice == 'Y' or choice == 'y' or choice == 'N' or choice == 'n'):
print('\n輸入格式有誤,請重試...')
continue
break
if choice == 'Y' or choice == 'y':
continue
else:
break
# 如果用戶的賬戶余額大于總金額
if user_balance >= amount:
user_balance -= amount
print('\n支付成功!您已成功購買 %s ,單價:%s 元,數(shù)量:%s,總金額:%s 元,賬戶余額:%s 元'
% (item_name, item_price, num, amount, user_balance))
lines = open('product_list.txt', 'r').readlines()
# 定位到用戶所購買的商品所在行,分割成列表賦值給select
select = lines[i-1].strip('\n').split(', ')
# 修改商品的庫存
select[-1] = (str(int(select[-1]) - int(num)) + '\n')
# 拼接成字符串
lines[i-1] = ', '.join(select)
# 將修改寫回文件
open('product_list.txt', 'w').writelines(lines)
lines = open('user_list.txt', 'r').readlines()
# 修改用戶余額
for line in lines:
if username in line.split(','): # 定位到用戶名所在行
j = lines.index(line) # 獲取用戶名所在行的行號索引
select = line.split(',') # 分割用戶名所在行賦值給列表select
select[-2] = str(user_balance) # 修改用戶余額
lines[j] = ','.join(select) # 修改后的列表拼接成字符串,覆蓋用戶名所在行
open('user_list.txt', 'w').writelines(lines) # 將修改寫回文件
else:
print('\n對不起,您的余額不足...')
else: # 加入購物車
j = 0
for j in range(len(shopping_cart)):
# 如果商品在購物車里面,更新商品數(shù)量
if item_name in shopping_cart[j]:
shopping_cart[j][2] = str(int(shopping_cart[j][2]) + int(num))
break
# 商品若不在購物車,則添加到購物車
else:
shopping_cart.append(item)
print('\n成功加入購物車!')
while True:
choice = input('\n是否繼續(xù)購買?(Y/N):')
if not (choice == 'Y' or choice == 'y' or choice == 'N' or choice == 'n'):
print('\n輸入格式有誤,請重試...')
continue
break
if choice == 'Y' or choice == 'y':
continue
else:
break
# 如果購物車不為空
if shopping_cart:
print('\n您的購物車里有以下寶貝:\n')
i = 1
total_sum = 0
for item in shopping_cart:
(commodity, price, number) = (item[0], item[1], item[2])
print((str(i) + '. ' + commodity).ljust(20) + ('單價:' + price + ' 元').ljust(15) + '數(shù)量:' + number)
total_sum += int(price) * int(number)
i += 1
print('\n合計:%d 元' % total_sum)
while True:
if_buy = input('\n是否結(jié)算?(Y/N):')
if not (if_buy == 'Y' or if_buy == 'y' or if_buy == 'N' or if_buy == 'n'):
print('\n輸入有誤,請重試...')
continue
break
while True:
# 結(jié)算
if if_buy == 'Y' or if_buy == 'y':
count = 0
cancel = False
while count < 3:
user_pay_passwd = getpass.getpass('\n請輸入支付密碼,或輸入 c 放棄支付:')
if user_pay_passwd == 'c':
print('\n取消支付成功...')
cancel = True
break
elif user_pay_passwd != info[3]:
if count != 2:
print('\n密碼錯誤,請重試,您還有 %d 次機會...' % (2-count))
count += 1
else:
break
if cancel:
if_payed = False
elif count == 3:
with open('lock_list.txt', 'w') as lock_file:
lock_file.write(username + '\n')
exit('\n密碼錯誤,賬戶已被鎖定...')
else:
if total_sum <= user_balance:
user_balance -= total_sum
print('\n支付成功!您已成功購買以下商品:\n')
i = 1
for item in shopping_cart:
(commodity, price, number) = (item[0], item[1], item[2])
print((str(i) + '. ' + commodity).ljust(20) +
('單價:' + price + ' 元').ljust(15) + '數(shù)量:' + number)
lines = open('product_list.txt', 'r').readlines()
for line in lines: # 修改商品庫存
if commodity in line.split(', '): # 定位到商品所在行
j = lines.index(line) # 獲取商品所在行的行號索引
select = line.split(', ') # 商品所在行分割為字符串列表
select[-1] = (str(int(select[-1]) - int(number)) + '\n') # 修改商品庫存
lines[j] = ', '.join(select) # 將修改后的字符串列表組成字符串
open('product_list.txt', 'w').writelines(lines) # 把修改寫回文件
i += 1
lines = open('user_list.txt', 'r').readlines()
for line in lines: # 用戶余額寫入文件
if username in line.split(','):
j = lines.index(line)
select = line.split(',')
select[-2] = str(user_balance)
lines[j] = ','.join(select)
open('user_list.txt', 'w').writelines(lines)
exit('\n合計:%d 元, 賬戶余額:%d 元' % (total_sum, user_balance))
# 不結(jié)算
else:
print('\n您有一筆未支付訂單...')
while True:
choice = input('\n是否進行支付?(Y/N):')
if not (choice == 'Y' or choice == 'y' or choice == 'N' or choice == 'n'):
print('\n輸入有誤,請重試...')
continue
break
if choice == 'n' or choice == 'N':
exit('\n訂單已取消,感謝光臨購物商城,再見...')
else:
if_buy = 'Y'
continue
if not if_payed:
print('\n您有一筆未支付訂單...')
while True:
choice = input('\n是否進行支付?(Y/N):')
if not (choice == 'Y' or choice == 'y' or choice == 'N' or choice == 'n'):
print('\n輸入有誤,請重試...')
continue
break
if choice == 'n' or choice == 'N':
exit('\n訂單已取消,感謝光臨購物商城,再見...')
else:
if_buy = 'Y'
continue
# 商家入口
if entrance == '2':
seller_name = ''
# 登錄接口
count = 0
while count < 3:
seller_name = input('\n用戶名:')
with open('lock_list.txt', 'r') as lock_file:
for lock_line in lock_file:
if seller_name == lock_line.strip('\n'):
exit('\n用戶名 %s 已被鎖定,請聯(lián)系管理員...' % seller_name)
seller_file = open('seller_list.txt', 'r')
login = False
for seller_line in seller_file:
(seller, passwd) = seller_line.strip('\n').split(',')
if seller_name == seller:
n = 0
while n < 3:
password = getpass.getpass('密碼:')
# 登錄成功,跳出while循環(huán)
if password == passwd:
print('\n歡迎 %s 登錄商城' % seller_name)
login = True
break
else:
if n != 2:
print('\n密碼錯誤,請重試,您還有 %d 次機會' % (2-n))
n += 1
# n = 3,鎖定用戶名
else:
open('lock_list.txt', 'w').write(seller_name + '\n')
exit('\n錯誤次數(shù)過多,賬戶已被鎖定...')
# 登錄成功,跳出for循環(huán)
if login:
break
# 用戶名不存在
else:
if count != 2:
print('\n用戶名不存在,請重試,您還有 %d 次機會' % (2-count))
# 登錄成功,跳出while循環(huán)
if login:
break
count += 1
else:
exit('\n錯誤次數(shù)過多,程序已退出...')
# 商品列表編輯程序
L = []
# 存放商品列表,初始為空
commodity_list = []
index = 1
print('\n您的貨架上有以下商品:\n')
print_product_list()
while True:
choice = input('\n是否編輯您的商品列表?(Y/N):')
if not (choice == 'Y' or choice == 'y' or choice == 'N' or choice == 'n'):
print('\n輸入有誤,請重試...')
continue
break
if choice == 'Y' or choice == 'y':
while True:
print('\n請選擇(輸入 q 退出):\n')
print('1. 上架新品\n\n2. 下架商品\n\n3. 修改商品信息')
choice = input('\n>>>')
if not (choice == '1' or choice == '2' or choice == '3' or choice == 'q'):
print('輸入有誤,請重試...')
continue
# 上架新品
if choice == '1':
while True:
if_add = False # 是否添加商品的標志,初始為False
new_commodity = input('\n輸入商品名:')
product_file = open('product_list.txt', 'r')
for product_line in product_file:
commodity = product_line.strip('\n').split(', ')[0] # 獲取商品列表中的商品名
if new_commodity == commodity:
print('\n此商品已在貨架上...')
continue
else:
while True:
if_sure = input('\n確定上架新品 %s 嗎?(Y/N):' % new_commodity)
if not (if_sure == 'Y' or if_sure == 'y' or if_sure == 'N' or if_sure == 'n'):
print('\n輸入有誤,請重試...')
continue
break
# 確定上架新品
if if_sure == 'Y' or if_sure == 'y':
while True: # 輸入單價
price = input('\n請輸入單價:')
if not price.isdigit():
print('\n輸入有誤,請重試...')
continue
break
while True: # 輸入庫存
stock = input('\n請輸入庫存:')
if not stock.isdigit():
print('\n輸入有誤,請重試...')
continue
break
new_line = '\n' + new_commodity + ', ' + price + ', ' + stock
open('product_list.txt', 'a').writelines(new_line)
print('\n成功上架新品 %s ,單價 %s 元,庫存 %s 件' % (new_commodity, price, stock))
while True:
option = input('\n是否繼續(xù)添加?(Y/N):')
if not (option == 'Y' or option or option == 'N' or option == 'n'):
print('\n輸入有誤,請重試...')
continue
break
if option == 'Y' or option == 'y':
if_add = True
break # 跳出for循環(huán)
else:
break
# 取消上架新品
else:
if_add = False
break # 跳出for循環(huán)
product_file.close()
if if_add is True:
continue
else:
break # 跳出while循環(huán)
# 下架商品
elif choice == '2':
while True:
del_num = input('\n請輸入您想下架商品的序號:')
if not (del_num.isdigit() or int(del_num) > 0 and int(del_num) <= len(commodity_list)):
print('\n輸入有誤,請重試...')
continue
break
del_num = int(del_num)
del_commodity = commodity_list[del_num - 1][0]
with open('product_list.txt', 'r') as old_file:
with open('product_list.txt', 'r+') as new_file:
current_line = 0
# 定位到需要刪除的行
while current_line < (del_num - 1):
old_file.readline()
current_line += 1
# 當(dāng)前光標在被刪除行的行首,記錄該位置
seek_point = old_file.tell()
# 設(shè)置光標位置
new_file.seek(seek_point, 0)
# 讀需要刪除的行,光標移到下一行行首
old_file.readline()
# 被刪除行的下一行讀給 next_line
next_line = old_file.readline()
# 連續(xù)覆蓋剩余行,后面所有行上移一行
while next_line:
new_file.write(next_line)
next_line = old_file.readline()
# 寫完最后一行后截斷文件,因為刪除操作,文件整體少了一行,原文件最后一行需要去掉
new_file.truncate()
print('\n您已成功下架 %s !' % del_commodity)
# 修改商品信息
elif choice == '3':
# 修改商品信息
def mod_commodity_info(i, j):
i = int(i)
j = int(j)
with open('product_list.txt', 'r+') as f:
current_line = 0
while current_line < i - 1:
f.readline()
current_line += 1
seek_point = f.tell()
f.seek(seek_point, 0)
# 修改商品名
if j == 1:
update_line = mod_name() + ', ' + commodity_list[i-1][1] + ', ' + commodity_list[i-1][2] + '\n'
# 修改商品價格
elif j == 2:
update_line = commodity_list[i-1][0] + ', ' + mod_price() + ', ' + commodity_list[i-1][2] + '\n'
# 修改商品庫存
else:
update_line = commodity_list[i-1][0] + ', ' + commodity_list[i-1][1] + ', ' + mod_stock() + '\n'
f.write(update_line)
return
def mod_name():
new_name = input("\n請輸入新的商品名:")
return new_name
def mod_price():
new_price = input("\n請輸入新的商品單價:")
return new_price
def mod_stock():
new_stock = input("\n請輸入新的商品庫存:")
return new_stock
# 修改商品單價
def mod_commodity_price(i):
i = int(i)
with open('product_list.txt', 'r+') as f:
current_line = 0
while current_line < i -1:
f.readline()
current_line += 1
seek_point = f.tell()
f.seek(seek_point, 0)
new_price = input()
while True:
i = input("\n請輸入需要編輯的商品序號(輸入 c 取消):")
if not (i.isdigit or i == 'c' or int(i) > 0 and int(i) <= len(commodity_list)):
print("\n輸入有誤,請重試...")
continue
elif i == 'c':
break
else:
while True:
j = input("\n請選擇需要編輯的選項(輸入 c 取消):\n\n1. 商品名\n\n2. 單價\n\n3. 庫存\n\n>>>")
if not (j == 'c' or j == '1' or j == '2' or j == '3'):
print("\n輸入有誤,請重試...")
continue
break
if j == 'c':
break
else:
mod_commodity_info(i, j)
else:
exit('\n您已退出商城...')
else:
exit('\n您已退出商城...')
以上這篇Python 實現(xiàn)購物商城,含有用戶入口和商家入口的示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- python+selenium小米商城紅米K40手機自動搶購的示例代碼
- python框架Django實戰(zhàn)商城項目之工程搭建過程圖文詳解
- python簡單商城購物車實例代碼
- python爬蟲框架scrapy實戰(zhàn)之爬取京東商城進階篇
- python爬蟲實戰(zhàn)之爬取京東商城實例教程
- python 實現(xiàn)網(wǎng)上商城,轉(zhuǎn)賬,存取款等功能的信用卡系統(tǒng)
- python實現(xiàn)簡單購物商城
- python抓取京東商城手機列表url實例代碼
- python實現(xiàn)淘寶購物系統(tǒng)
- Python實現(xiàn)購物系統(tǒng)(示例講解)
- Python實現(xiàn)信用卡系統(tǒng)(支持購物、轉(zhuǎn)賬、存取錢)
- 基于Python實現(xiàn)的購物商城管理系統(tǒng)
相關(guān)文章
python實現(xiàn)微信自動回復(fù)及批量添加好友功能
這篇文章主要介紹了python實現(xiàn)微信自動回復(fù)及python 批量生成微信添加好友截圖功能的實例代碼,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07
Python Matplotlib繪圖基礎(chǔ)知識代碼解析
這篇文章主要介紹了Python Matplotlib繪圖基礎(chǔ)知識代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08
使用Scrapy框架爬取網(wǎng)頁并保存到Mysql的實現(xiàn)
本文主要介紹了使用Scrapy框架爬取網(wǎng)頁并保存到Mysql的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07

