编写购物商城(1)
程序员文章站
2022-04-23 22:24:03
...
作业:购物商城
商品展示,价格
买,加入购物车
付款,钱不够
具体实现了如下功能:
1、可购买的商品信息显示
2、显示购物车内的商品信息、数量、总金额
3、购物车内的商品数量进行增加、减少和商品的删除
4、用户余额的充值
5、用户购买完成进行结账,将最终余额回写到用户文件中。
一、用户文件说明:
kevin 123 50000sky 123 54000mobi 123 80000
其中第一列为用户名,第二列为密码,第三列为帐户余额。
二、流程图如下:
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 = '''******************************************************************************* \033[32;1m欢迎来到小猪猪购物商城\033[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 = 1print("商品列表:") 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 += 1print("=================================================================================================")return local_dict def cart_goods_show(show_dict):'''显示购物车商品,并加上数字编号'''show_all_sum = 0show_all_num = 0'''对商品列表进行遍历并加上数字编号'''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[0],v[1],v[2],v[3],v[4])) show_all_num += v[4] show_all_num += 1print("请确认你购买的商品,总金额:%d元"%(show_all_sum))return (show_all_sum,show_all_num) def cart_goods_modify(modify_dict,modify_goods_dict):'''购物车商品修改列表'''a_flag = 1while a_flag: index = input("请输入商品编号|完成修改(q):" %modify_dict[index][2])if len(index) != 0: index = input_handle(index)if index == "q":breakelif index in modify_dict: b_flag = 1name = modify_dict[index][0]while b_flag: num = input("请输入新的商品数量(最大值为%d)|完成修改(q):" %modify_dict[index][2])if len(num) != 0: num = input_handle(num)if num == 'q':breakelif num == 0: modify_goods_dict[name]['num'] = modify_dict[index][2] del modify_dict[index] b_flag = 0elif num > 0 and num <= modify_dict[index][2]: modify_dict[index][3] = num modify_dict[index][4] = modify_dict[index][1] * num modify_goods_dict[name]['num'] = modify_dict[index][2] - num b_flag = 0else: passelse: passreturn (modify_dict,modify_goods_dict) def shopping_cart_show(my_cart,my_goods_dict):'''购物车展示'''print("欢迎来到你的购物车".center(80,"#")) goods_all_sum = 0goods_all_num = 0if 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: passelse: print("您当前的购物车为空".center(80,"#")) time.sleep(2)return (goods_all_sum,goods_all_num,my_goods_dict) def balance_recharge(recharge_init_balance,recharge_now_balance,recharge_money): recharge_flag = 1while recharge_flag: recharge_num = input("请输入充值金额|返回(b)|退出(q):")if len(recharge_num) != 0: recharge_num = input_handle(recharge_num)if recharge_num == "q": sys.exit(0) elif recharge_num == 'b':breakelif type(recharge_flag) is int and recharge_num > 0: recharge_init_balance += recharge_num recharge_now_balance += recharge_num recharge_money += recharge_num recharge_flag = 0print("充值成功,请查收".center(80,"#"))else: passreturn (recharge_init_balance,recharge_now_balance,recharge_money) def user_billing(billing_list,my_cart,billing_balance):'''结帐模块'''print("欢迎来到结帐模块".center(80,"#"))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(80,"#") %billing_balance)else: print("退出结算菜单,继续购物".center(80,"#")) time.sleep(2)else: print("您当前的购物车为空,无需结算!") time.sleep(2)'''主程序开始'''if __name__ == "__main__": goods_list = { 'iphone6': {'price':6000,'num':10,'sum':10}, 'ipad': {'price':3000,'num':20,'sum':20}, 'mi4': {'price':2000,'num':43,'sum':43}, 'huawei6_plus': {'price':1999,'num':8,'sum':8}, } i = 0while i < 3: #只要用户登录不超过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 = 0if user == username and password == passwd: user_shopping_cart = {} user_shopping_cart_count = 0recharge_value = 0line_num = user_list.index(user_line) first_flag = 1while 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) != 0: goods_index = input_handle(goods_index)if goods_index == 'q': sys.exit(0) 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_sumif now_balance < 0: print("您的余额不足,请及时充值!") time.sleep(2) 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][0],goods_output_dict[goods_index][1],goods_output_dict[goods_index][2]) print('【 编号:%-5d \t 名称:%-15s \t 价格:%-5d(元) \t 数量:%-5d(个)】' % (goods_index, goods_name, goods_price, goods_num)) second_flag = 1while second_flag: buy_num = input('请输入购买商品个数(最大值为%d) | 返回(b) | 退出(q): ' % goods_num)if len(buy_num) != 0: buy_num = input_handle(buy_num)if buy_num == 'q': sys.exit(0) elif buy_num == 'b':breakelif type(buy_num) is int and buy_num > 0 and buy_num <= goods_num: my_goods_sum = goods_price * buy_numif 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 += 1'''购物车商品数量加一'''user_shopping_cart[goods_index] = [goods_name,goods_price,goods_num,buy_num,my_goods_sum]else: user_shopping_cart[goods_index][3] += buy_num user_shopping_cart[goods_index][4] += my_goods_sum now_balance -= my_goods_sum goods_list[goods_name]['num'] -= buy_num second_flag = 0else:breakelse: print("您的余额不足,请充值或重新选择,谢谢!") time.sleep(2)else: passelse: passelse:if i != 2: print('用户或密码错误,请重新输入,还有 %d 次机会' % (2 - i)) i += 1else: sys.exit('用户或密码输入错误超过三次,退出系统,欢迎下次光临')
上述代码不难,难的是思路,思路很重要,要知道如何一步一步去操作,用的也都是我们常用的知识,其实归根揭底我们写程序,大部分使用的都是字符串,字典,列表的功能。还有一些模块之类的。在写程序的过程中,思路显得尤为重要。知道了思路,就考虑如何使用代码去实现,上面程序中学到了如下知识点;
1、输出格式对其:print("%-5s %-15s %-10s %-10s %-10s" %("编号","商品名称","商品价格(元)","商品总数量(个)","商品剩余数量(个)")),上面代码能够实现对其格式的功能,让我们输出的字符串格式统一,比如上述代码中,编号左对齐5个字符,商品名称左对齐15个字符等等;
2、str.center()的使用,如print("欢迎来到你的购物车".center(80,"#"));
以上就是编写购物商城(1)的详细内容,更多请关注其它相关文章!