函数作业:
1、复习函数参数的使用
2、实现如下功能
编写用户注册函数,实现功能
1、在函数内接收用户输入的用户名、密码、余额
要求用户输入的用户名必须为字符串,并且保证用户输入的用户名不与其他用户重复
要求用户输入两次密码,确认输入一致
要求用户输入的余额必须为数字
2、要求注册的用户信息全部存放于文件中
def func(): tag = True # 取出当前文件所有的用户名,用于判断后面用户是否已经存在 name_line = [] with open('db', 'rt', encoding='utf-8') as f_db: for line in f_db: line = line.strip('\n').split(':') name_line.append(line[0]) while tag: # 验证注册用户名的合法性 name_inp = input('username>>: ').strip() if not name_inp.isalpha(): print('用户名必须全是字符') continue if name_inp in name_line: print('用户名已注册') continue while tag: # 验证密码的合法性 pwd_inp = input('password>>: ') pwd_inp_chk = input('password>>: ') if pwd_inp != pwd_inp_chk: print('两次密码不一致') continue while tag: # 验证余额的合法性 balance = input('balance>>: ').strip() if not balance.isdigit(): print('必须为整数') continue # 以上条件全成立,则写入文件 with open('db', 'at', encoding='utf-8') as f_info: f_info.write('%s:%s:%s\n' % (name_inp, pwd_inp, balance)) print('注册成功') tag = False func()
编写用户转账函数,实现功能
1、传入源账户名(保证必须为str)、目标账户名(保证必须为str)、转账金额(保证必须为数字)
2、实现源账户减钱,目标账户加钱
def func_transfer(): import os tag = True #取出当前文件内所有的用户名,用于后面判断账号名是否存在 line_name = [] with open('db', 'rt', encoding='utf-8') as f_name: for line in f_name: line = line.strip('\n').split(':') line_name.append(line[0]) while tag: #验证转出账号名的合法性 name_s = input('转出账户名>>: ').strip() if not name_s.isalpha(): print('必须为纯字母') continue if name_s not in line_name: print('转出账户名不存在') continue #取出此账号名转账前的账号余额,用于后面判断后面转账金额是否足够 with open('db','rt',encoding='utf-8') as f_b: for line in f_b: line = line.strip('\n').split(':') if name_s == line[0]: balance = line[2] balance = int(balance) print('当前余额:%s' %balance) while tag: #验证转入账号名的合法性 name_d = input('转入账户名>>: ') if not name_d.isalpha(): print('必须为纯字母') continue if name_d not in line_name: print('转出账户名不存在') continue while tag: #验证转账金额是否充足 transfer_amount = input('转账金额>>: ') if not transfer_amount.isdigit(): print('转账金额必须为整数') continue transfer_amount = int(transfer_amount) if transfer_amount > balance: print('余额不足,从新输入') continue #上面的条件都符合,则修改文件 with open('db','rt',encoding='utf-8') as read_f,\ open('db.swap','wt',encoding='utf-8') as write_f: for line in read_f: line = line.strip('\n').split(':') if name_s == line[0]: line[2] = int(line[2]) - transfer_amount line[2] = str(line[2]) if name_d == line[0]: line[2] = int(line[2]) + transfer_amount line[2] = str(line[2]) line_new = ':'.join(line) line_new = line_new +'\n' write_f.write(line_new) os.remove('db') os.rename('db.swap','db') print('转账完成') tag = False func_transfer()
编写用户验证函数,实现功能
1、用户输入账号,密码,然后与文件中存放的账号密码验证
2、同一账号输错密码三次则锁定
3、这一项为选做功能:锁定的账号,在五分钟内无法再次登录
提示:一旦用户锁定,则将用户名与当前时间写入文件,例如: egon:1522134383.29839
实现方式如下:
import time
current_time=time.time()
current_time=str(current_time) #当前的时间是浮点数,要存放于文件,需要转成字符串
lock_user='%s:%s\n' %('egon',current_time)
然后打开文件
f.write(lock_user)
以后再次执行用户验证功能,先判断用户输入的用户名是否是锁定的用户,如果是,再用当前时间time.time()减去锁定的用户名后
的时间,如果得出的结果小于300秒,则直接终止函数,无法认证,否则就从文件中清除锁定的用户信息,并允许用户进行认证
import time import os name_info = [] with open('db','rt',encoding='utf-8') as f0: for line0 in f0: line0 = line0.strip('\n').split(':') name_info.append(line0[0]) # print(name_info) lock_users = [] with open('db_lock','rt',encoding='utf-8') as f_lock: for line1 in f_lock: line1 = line1.strip('\n').split(':') lock_users.append(line1[0]) # print(lock_users) tag = True while tag: name_inp = input('username>>: ').strip() if name_inp not in name_info: print('用户名不存在') continue if name_inp in lock_users: current_time = time.time() # print('用户已被锁定') with open('db_lock', 'rt', encoding='utf-8') as f_lock_time: for line2 in f_lock_time: line2 = line2.strip('\n').split(':') if name_inp == line2[0]: name_lock_time = line2[1] name_lock_time = float(name_lock_time) # print(name_lock_time,type(name_lock_time)) valid_time = current_time - name_lock_time #时间戳差值转为秒 if valid_time < 300: print('锁定状态') tag = False else: with open('db_lock','rt',encoding='utf-8') as f3,\ open('db_lock.swap','wt',encoding='utf-8') as f4: for line3 in f3: line3_new = line3.strip('\n').split(':') if name_inp != line3[0]: f4.write(line3) os.remove('db_lock') os.rename('db_lock.swap','db_lock') with open('db', 'rt', encoding='utf-8') as f1: for line in f1: line = line.strip('\n').split(':') if name_inp == line[0]: name_pwd = line[1] break count = 1 while count <= 3: pwd_inp = input('password>>: ') if pwd_inp == name_pwd: print('验证成功') tag = False break else: print('密码错误') count += 1 if count == 4: current_time = time.time() current_time = str(current_time) lock_user = '%s:%s\n' % (name_inp, current_time) with open('db_lock','at',encoding='utf-8') as f2: f2.write(lock_user) print('%s 用户已被锁定五分钟' %name_inp) tag = False
购物车
#******************购物车 import os product_list = [['Iphone7',5800], ['Coffee',30], ['疙瘩汤',10], ['Python Book',99], ['Bike',199], ['ViVo X9',2499], ] shopping_cart={} current_userinfo=[] db_file=r'db.txt' while True: print(''' 1 注册 2 登录 3 购物 ''') choice=input('请选择:').strip() if choice =='1': while True: name=input('username:') password=input('password:') conf_password=input('conf password') balance=input('balance:') if password ==conf_password: with open(db_file,'a') as f: f.write('%s,%s,%s\n'%(name,password,balance)) break else: print('两次密码不一致') elif choice =='2': count=0 tag=True while tag: if count ==3: print('错误过多,退出') break name=input('name') password=input('password') with open(db_file,'r') as f: for line in f: user_info=line.split(',') user_name=user_info[0] user_password=user_info[1] user_balance=int(user_info[2]) if user_name == name and user_password == password: current_userinfo=[user_name,user_balance] print('登录成功') print('用户信息为:',current_userinfo) tag=False break else: print('用户名密码错误') count+=1 elif choice == '3': if len(current_userinfo) == 0: print('\033[49m请先登陆...\033[0m') else: #登陆成功后,开始购物 uname_of_db=current_userinfo[0] balance_of_db=current_userinfo[1] print('尊敬的用户[%s] 您的余额为[%s],祝您购物愉快' %( uname_of_db, balance_of_db )) tag=True while tag: for index,product in enumerate(product_list): print(index,product) choice=input('输入商品编号购物,输入q退出>>: ').strip() if choice.isdigit(): choice=int(choice) if choice < 0 or choice >= len(product_list):continue pname=product_list[choice][0] pprice=product_list[choice][1] if balance_of_db > pprice: if pname in shopping_cart: # 原来已经购买过 shopping_cart[pname]['count']+=1 else: shopping_cart[pname]={'pprice':pprice,'count':1} balance_of_db-=pprice # 扣钱 current_userinfo[1]=balance_of_db # 更新用户余额 print(pname + " 添加到购物车,余额为: " + str(balance_of_db)) else: print("产品价格是{price},你还差{lack_price}".format( price=pprice, lack_price=(pprice - balance_of_db) )) print(shopping_cart) elif choice == 'q': print(""" ---------------------------------已购买商品列表--------------------------------- id 商品 数量 单价 总价 """) total_cost=0 for i,key in enumerate(shopping_cart): print('%22s%18s%18s%18s%18s' %( i, key, shopping_cart[key]['count'], shopping_cart[key]['pprice'], shopping_cart[key]['pprice'] * shopping_cart[key]['count'] )) total_cost+=shopping_cart[key]['pprice'] * shopping_cart[key]['count'] print(""" 您的总花费为: %s 您的余额为: %s ---------------------------------end--------------------------------- """ %(total_cost,balance_of_db)) while tag: inp=input('确认购买(yes/no?)>>: ').strip() if inp not in ['Y','N','y','n','yes','no']:continue if inp in ['Y','y','yes']: # 将余额写入文件 src_file=db_file dst_file=r'%s.swap' %db_file with open(src_file,'r',encoding='utf-8') as read_f,\ open(dst_file,'w',encoding='utf-8') as write_f: for line in read_f: if line.startswith(uname_of_db): l=line.strip('\n').split(',') l[-1]=str(balance_of_db) line=','.join(l)+'\n' write_f.write(line) os.remove(src_file) os.rename(dst_file,src_file) print('购买成功,请耐心等待发货') shopping_cart={} current_userinfo=[] tag=False else: print('非法输入') # enumerate(列表或字典)
# 作业一: 三级菜单
# 要求:
# 打印省、市、县三级菜单
# 可返回上一级
# 可随时退出程序
menu = { '北京': { '海淀': { '五道口': { 'soho': {}, '网易': {}, 'google': {} }, '中关村': { '爱奇艺': {}, '汽车之家': {}, 'youku': {}, }, '上地': { '百度': {}, }, }, '昌平': { '沙河': { '老男孩': {}, '北航': {}, }, '天通苑': {}, '回龙观': {}, }, '朝阳': {}, '东城': {}, }, '上海': { '闵行': { "人民广场": { '炸鸡店': {} } }, '闸北': { '火车战': { '携程': {} } }, '浦东': {}, }, '山东': {}, } layer = [menu,] #核心功能 while True: if len(layer) == 0:break current_layer = layer[-1] #核心功能 for k in current_layer: #核心功能 print(k) #核心功能 choice = input('选择>>: ').strip() #核心功能 if choice == 'q': break if choice == 'b': layer.pop() continue if not current_layer[choice]:break layer.append(current_layer[choice]) #核心功能