用函数完成登录注册以及购物车的功能. 难度系数一般
# 要求:
# 1, 启动程序, 用户可选择四个选项: 登录, 注册, 购物, 退出.
# 2, 用户注册, 用户名不能重复, 注册成功之后, 用户名密码记录到文件中.
# 3, 用户登录, 用户名密码从文件中读取,进行三次验证, 验证不成功则退出整个程序.
# 4, 用户登录成功之后才能选择购物功能进行购物, 购物功能( 就是将购物车封装到购物的 函数中).
# 5, 退出则是退出整个程序.
# 欢迎计入购物系统:
# 1. 登录
# 2. 注册
# 3. 购物
# 4. 退出
goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998}, ] shopping_car = [] shopp_dic = {} flag = True def one(): ‘‘‘ 打印导航 :return: ‘‘‘ print(‘‘‘欢迎进入老男孩购物系统: 1.登录 2.注册 3.购物 4.退出 ‘‘‘) def register(): ‘‘‘ 注册函数 :return: ‘‘‘ while 1: username = input(‘请输入用户名:‘) password = input(‘请输入密码:‘) with open(‘user‘,‘r+‘,encoding=‘utf-8‘) as f: for line in f: new_line = line.split(‘&&‘) if username == new_line[0]: print(‘用户名已存在,请重新输入‘) break else: f.write(‘\n‘+username+‘&&‘+password) print(‘注册成功‘) break def login(): ‘‘‘ 登录函数 :return: ‘‘‘ global flag count = 1 while count <=3: username = input(‘请输入用户名:‘) password = input(‘请输入密码:‘) with open(‘user‘,‘r‘,encoding=‘utf-8‘) as f: for line in f: new_line = line.strip().split(‘&&‘) if username == new_line[0] and password == new_line[1]: print(‘登录成功!‘) flag = False break else: print(‘用户名或密码错误,请重新输入,还有%s次机会‘ % (3-count)) count += 1 continue break def shopping(): ‘‘‘ 购物函数 :return: ‘‘‘ if flag == False: #判断有没有登录 while True: money = input(‘请输入存款:‘).strip() if 0 < int(money) and money.isdigit(): # 判断输入的金额是否大于0,是否是数字 for dic in goods: print(goods.index(dic) + 1, dic[‘name‘], dic[‘price‘]) # 打印所有商品 while True: choice = input(‘请输入要选择的商品序号:‘).strip() if 0 < int(choice) <= len(goods) and choice.isdigit(): for shopp_dic in shopping_car: # shopp_dic是shopping_car列表中的每一个字典 if goods[int(choice) - 1][‘name‘] == shopp_dic[‘name‘]: shopp_dic[‘num‘] += 1 # 如果选择的商品名字跟字典中的商品名字是一样的,则该商品的数量+1 break else: # 如果选择的商品没有在购物车,则加入购物车, shopp_dic = {} shopp_dic[‘name‘] = goods[int(choice) - 1][‘name‘] shopp_dic[‘price‘] = goods[int(choice) - 1][‘price‘] shopp_dic[‘num‘] = 1 # 第一次加入商品初始数量为1 shopping_car.append(shopp_dic) choice2 = input(‘是否继续选择Y继续,N结算:‘).strip() if choice2.upper() == ‘Y‘: # 选择继续购买 for dic in goods: print(goods.index(dic) + 1, dic[‘name‘], dic[‘price‘]) # 打印所有商品 continue else: for shopp_dic in shopping_car: print(‘您已选择以下商品:‘) print(shopp_dic) # 打印已加购物车的商品 if int(money) > shopp_dic[‘price‘] * shopp_dic[‘num‘]: # 如果输入的总钱数大于商品总金额,告知共花费多少,剩余多少 surplus = int(money) - shopp_dic[‘price‘] * shopp_dic[‘num‘] print(‘共花费%s元,还剩%s元‘ % (shopp_dic[‘price‘] * shopp_dic[‘num‘], surplus)) else: # 总金额不足 owe = shopp_dic[‘price‘] * shopp_dic[‘num‘] - int(money) print(‘余额不足,还缺%s元‘ % owe) break else: print(‘输入有误,请重新输入‘) else: # 输入的数字小于0并且或者不是数字的话,重新输入 print(‘输入有误,请重新输入‘) break else: #没有登录的话执行登录函数 print(‘您还没有登录,请先登录!‘) login() def main(): while True: one() choice = input(‘请输入选项:‘) if choice == ‘1‘: login() continue elif choice == ‘2‘: register() elif choice == ‘3‘: shopping() elif choice == ‘4‘: break else: print(‘输入有误,请重新输入‘) break main()
原文:https://www.cnblogs.com/lianghui-lianghui/p/9515100.html