作业:购物商城
商品展示,价格
买,加入购物车
付款,钱不够
具体实现了如下功能:
1、可购买的商品信息显示
2、显示购物车内的商品信息、数量、总金额
3、购物车内的商品数量进行增加、减少和商品的删除
4、用户余额的充值
5、用户购买完成进行结账,将最终余额回写到用户文件中。
一、用户文件说明:
kevin
sky
mobi
其中第一列为用户名,第二列为密码,第三列为帐户余额。
二、流程图如下:
import sys,os,getpass,time def input_handle(s):
'''用户输入字符数字转化为数字'''
if s.isdigit(): #判断用户输入是否是字符数字
s = int(s) #是的话就进行转换
return s def framework(user="",init_money='',now_money='',recharge_money='',value=''):
'''架构函数,展示用户的基本信息'''
os.system("clear")
init_money = int(init_money)
now_money = int(now_money)
recharge_money = int(recharge_money)
message = '''
******************************************************************************* \[;1m欢迎来到小猪猪购物商城\[0m *******************************************************************************
会员:%s\t金额:%d\t当前余额:%d\t充值金额:%d\t购物车:%d
''' %(user,init_money,now_money,recharge_money,value)
print(message) def goods_list_show(my_dict):
'''商品展示模块,用于展示商品'''
local_dict = {}
'''对商品列表进行遍历并加上数字编号'''
i =
print("商品列表:")
print("=================================================================================================")
print("%-5s %-15s %-10s %-10s %-10s" %("编号","商品名称","商品价格(元)","商品总数量(个)","商品剩余数量(个)"))
for k in my_dict.keys():
v = my_dict[k]
if type(v) == dict:
print("%-5s %-20s %-15d %-18d %-10d" %(i,k,v['price'],v['num'],v['sum']))
local_dict[i] = [k,v["price"],v['num'],v['sum']]
i +=
print("=================================================================================================")
return local_dict def cart_goods_show(show_dict):
'''显示购物车商品,并加上数字编号'''
show_all_sum =
show_all_num =
'''对商品列表进行遍历并加上数字编号'''
message = ('编号',"商品名称","商品价格(元)","商品总数量(个)","购买数量(个)","购买金额(元)")
print("%-5s \t %-20s \t %-10s \t %-10s \t %-10s \t %-10s" %message)
for k in show_dict:
v = show_dict[k]
if type(v) is dict:
print("%-5s \t %-10s \t %-10d \t %-10d \t %-10d \t %-10d" %(k,v[],v[],v[],v[],v[]))
show_all_num += v[]
show_all_num +=
print("请确认你购买的商品,总金额:%d元"%(show_all_sum))
return (show_all_sum,show_all_num) def cart_goods_modify(modify_dict,modify_goods_dict):
'''购物车商品修改列表'''
a_flag =
while a_flag:
index = input("请输入商品编号|完成修改(q):" %modify_dict[index][])
if len(index) != :
index = input_handle(index)
if index == "q":
break
elif index in modify_dict:
b_flag =
name = modify_dict[index][]
while b_flag:
num = input("请输入新的商品数量(最大值为%d)|完成修改(q):" %modify_dict[index][])
if len(num) != :
num = input_handle(num)
if num == 'q':
break
elif num == :
modify_goods_dict[name]['num'] = modify_dict[index][]
del modify_dict[index]
b_flag =
elif num > and num <= modify_dict[index][]:
modify_dict[index][] = num
modify_dict[index][] = modify_dict[index][] * num
modify_goods_dict[name]['num'] = modify_dict[index][] - num
b_flag =
else:
pass
else:
pass
return (modify_dict,modify_goods_dict) def shopping_cart_show(my_cart,my_goods_dict):
'''购物车展示'''
print("欢迎来到你的购物车".center(,"#"))
goods_all_sum =
goods_all_num =
if my_cart:
'''调用购物车商品列表函数,并返回商品总金额和总数量'''
(goods_all_sum,goods_all_num) = cart_goods_show(my_cart)
choice = input("请进行如下操作:修改记录(c)|继续购物(!c)")
if choice == "c":
(my_shop_cart,my_goods_dict) = cart_goods_modify(my_cart,my_goods_dict)
(goods_all_sum,goods_all_num) = cart_goods_show(my_cart)
else:
pass
else:
print("您当前的购物车为空".center(,"#")) time.sleep()
return (goods_all_sum,goods_all_num,my_goods_dict) def balance_recharge(recharge_init_balance,recharge_now_balance,recharge_money):
recharge_flag =
while recharge_flag:
recharge_num = input("请输入充值金额|返回(b)|退出(q):")
if len(recharge_num) != :
recharge_num = input_handle(recharge_num)
if recharge_num == "q":
sys.exit()
elif recharge_num == 'b':
break
elif type(recharge_flag) is int and recharge_num > :
recharge_init_balance += recharge_num
recharge_now_balance += recharge_num
recharge_money += recharge_num
recharge_flag =
print("充值成功,请查收".center(,"#"))
else:
pass
return (recharge_init_balance,recharge_now_balance,recharge_money) def user_billing(billing_list,my_cart,billing_balance):
'''结帐模块'''
print("欢迎来到结帐模块".center(,"#"))
if my_cart:
'''调用购物车商品列表函数'''
cart_goods_show(my_cart)
billing_flag = input("请确认是否商品结算(y|n):")
if billing_flag == "y":
billing_file = open("info.txt",'w')
for user_info in billing_list:
billing_file.writelines(user_info)
billing_file.close()
sys.exit("结帐成功,您当前余额:%d".center(,"#") %billing_balance)
else:
print("退出结算菜单,继续购物".center(,"#"))
time.sleep()
else:
print("您当前的购物车为空,无需结算!")
time.sleep() '''主程序开始'''
if __name__ == "__main__":
goods_list = {
'iphone6': {'price':,'num':,'sum':},
'ipad': {'price':,'num':,'sum':},
'mi4': {'price':,'num':,'sum':},
'huawei6_plus': {'price':,'num':,'sum':},
}
i =
while i < : #只要用户登录不超过3次就不断循环
username = input("请输入用户名:")
password = input("请输入密码:")
user_file = open("info.txt",'r')
user_list = user_file.readlines()
user_file.close() for user_line in user_list:
'''分别获取当前账号、密码和余额信息'''
user,passwd,init_balance = user_line.strip('\n').split()
init_balance = int(init_balance)
now_balance = init_balance
my_goods_sum = if user == username and password == passwd:
user_shopping_cart = {}
user_shopping_cart_count =
recharge_value =
line_num = user_list.index(user_line)
first_flag = while first_flag:
'''调用框架函数输出用户信息'''
framework(username,init_balance,now_balance,recharge_value,user_shopping_cart_count)
goods_output_dict = goods_list_show(goods_list) #输出商品信息
goods_index = input("请选择菜单:输入商品编号 | 购物车(c) | 余额充值(r) | 结账(b) | 退出(q) :") if len(goods_index) != :
goods_index = input_handle(goods_index) if goods_index == 'q':
sys.exit() elif goods_index == 'c':
'''调用购物车显示函数,并返回购物车商品总金额'''
(my_goods_sum,user_shopping_cart_count,goods_list) = shopping_cart_show(user_shopping_cart,goods_list)
now_balance = init_balance - my_goods_sum
if now_balance < :
print("您的余额不足,请及时充值!")
time.sleep() elif goods_index == 'r':
(init_balance,now_balance,recharge_value) = balance_recharge(init_balance,now_balance,recharge_value) elif goods_index == 'b':
'''更新用户的余额'''
user_list[line_num] = user + ' ' + passwd + ' ' + repr(now_balance) + '\n'
user_billing(user_list,user_shopping_cart,now_balance) elif goods_index in goods_output_dict:
'''取出goods_index商品列表信息并进行赋值和展示'''
(goods_name,goods_price,goods_num) = (goods_output_dict[goods_index][],goods_output_dict[goods_index][],goods_output_dict[goods_index][])
print('【 编号:%-5d \t 名称:%-15s \t 价格:%-5d(元) \t 数量:%-5d(个)】' % (goods_index, goods_name, goods_price, goods_num)) second_flag =
while second_flag:
buy_num = input('请输入购买商品个数(最大值为%d) | 返回(b) | 退出(q): ' % goods_num)
if len(buy_num) != :
buy_num = input_handle(buy_num) if buy_num == 'q':
sys.exit()
elif buy_num == 'b':
break elif type(buy_num) is int and buy_num > and buy_num <= goods_num:
my_goods_sum = goods_price * buy_num
if my_goods_sum <= now_balance:
print('购买商品 %s 总价格为 : %d' % (goods_name, my_goods_sum))
add_flag = input("请确认是否加入购物车(y | n):")
if add_flag == "y":
'''判断购物车不存在该商品'''
if goods_index not in user_shopping_cart:
user_shopping_cart_count +=
'''购物车商品数量加一'''
user_shopping_cart[goods_index] = [goods_name,goods_price,goods_num,buy_num,my_goods_sum]
else:
user_shopping_cart[goods_index][] += buy_num
user_shopping_cart[goods_index][] += my_goods_sum now_balance -= my_goods_sum goods_list[goods_name]['num'] -= buy_num
second_flag =
else:
break else:
print("您的余额不足,请充值或重新选择,谢谢!")
time.sleep() else:
pass
else:
pass
else:
if i != :
print('用户或密码错误,请重新输入,还有 %d 次机会' % ( - i))
i +=
else:
sys.exit('用户或密码输入错误超过三次,退出系统,欢迎下次光临')
上述代码不难,难的是思路,思路很重要,要知道如何一步一步去操作,用的也都是我们常用的知识,其实归根揭底我们写程序,大部分使用的都是字符串,字典,列表的功能。还有一些模块之类的。在写程序的过程中,思路显得尤为重要。知道了思路,就考虑如何使用代码去实现,上面程序中学到了如下知识点;
1、输出格式对其:print("%-5s %-15s %-10s %-10s %-10s" %("编号","商品名称","商品价格(元)","商品总数量(个)","商品剩余数量(个)")),上面代码能够实现对其格式的功能,让我们输出的字符串格式统一,比如上述代码中,编号左对齐5个字符,商品名称左对齐15个字符等等;
2、str.center()的使用,如print("欢迎来到你的购物车".center(80,"#"));