一、校验输入的是否为小数
#小数 1.5 1.34 -0.5 -8.4 #小数点个数为1 小数点左边和右边都是整数 # 负号开头,且只有一个负号 def check_float(num): s=str(num) #将传入的内容转成字符串,保证下面能用字符串的方法 if s.count('.')==1: left,right=s.split('.') if left.isdigit() and right.isdigit(): return '正小数' elif s.startswith('-') and s.count('-')==1 and left[1:].isdigit() and right.isdigit(): return '负小数' return '不是小数' print(check_float('a.9')) #不是小数 print(check_float('-1.7')) #负小数 print(check_float('3')) #不是小数 print(check_float('8.2')) #正小数 print(check_float('0.3.5')) #不是小数
二、写一个函数,函数的功能是生成一批密码,存到文件里面
(1)密码复杂度要求
1、长度在,8-16位之间
2、密码必须包括大写字母、小写字母、数字、特殊字符
3、密码不能重复
(2)生成的密码保存到文件里面
#思路一 #1、生成长度为n位的密码,分别从大写字母、小写字母、数字、特殊字符中各取一个 #2、再从所有字符里面取n-4个 #思路二 # 1、all_str ='0-9 a-z A-Z 特殊字符' #2、随机取八位,判断里面是否包含大写字母、小写字母、数字、特殊字符 (集合分别取交集) #3、若有交集,则存起来;否则重新取 import random,string def gen_password1(): pwd_len = random.randint(8,16) upper = random.sample(string.ascii_uppercase,1) lower = random.sample(string.ascii_lowercase,1) digit = random.sample(string.digits,1) punctuation = random.sample(string.punctuation,1) other = random.sample(string.ascii_letters + string.digits + string.punctuation,pwd_len-4) res=upper+lower+digit+punctuation+other random.shuffle(res) #打乱顺序 return ''.join(res) def gen_password2(): pwd_len = random.randint(8, 16) all_str = string.ascii_letters + string.digits + string.punctuation res = set(random.sample(all_str, pwd_len)) if res & set(string.ascii_uppercase) and res & set(string.ascii_lowercase) and res & set(string.digits) and res & set(string.punctuation): return ''.join(res) return gen_password2() #用递归的时候,加上return,否则会出现返回值为None的情况 num = int(input('请输入要产生多少条密码:').strip()) all_pwds = set() while len(all_pwds)!=num : res = gen_password2()+'\n' all_pwds.add(res) with open('passwords.txt','a+',encoding='utf-8') as fw: fw.writelines(all_pwds)
三、写一个函数,函数的功能生成一批双色球号码
(1)中奖号码由6个红色球号码和1个蓝色球号码组成,eg:蓝球: 05 红球: 01 03 05 17 18 32
红球的范围是 1-33
篮球的范围是:1-16
(2)产生的每组号码不能重复
import random def gen_seq(): all_redBall=[str(i).zfill(2) for i in range(0,34)] #用到了列表生成式 all_blueBall=[str(i).zfill(2) for i in range(0,17)] red = random.sample(all_redBall,6) blue = random.choice(all_blueBall) red =' '.join(red) return '红球:%s 蓝球:%s'%(red,blue) num = int(input('请输入要产生多少条双色球:').strip()) all_seq = set() while len(all_seq)!=num : res = gen_seq()+'\n' all_seq.add(res) with open('Balls.txt','a+',encoding='utf-8') as fw: fw.writelines(all_seq)
PS:列表生成式
list = [i+1 for i in range(0,10)]
print(list) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
四、写一个清理日志的程序,清理该目录下三天前的文件,文件名格式是xxx.2018-03-05.log,每天会产生一个当天日期命名的文件
1 import os,time 2 3 res = os.walk('D:\logs') 4 5 current_ftime =time.strftime('%Y-%m-%d') 6 time_tuple =time.strptime(current_ftime,'%Y-%m-%d') 7 current_tstamp= time.mktime(time_tuple) 8 point=current_tstamp - 3*24*60*60 9 10 for cur_path,dirs,files in res: 11 for file_name in files: 12 format_time= file_name.split('_')[1].split('.')[0] 13 time_tuple =time.strptime(format_time,'%Y-%m-%d') 14 time_stamp= time.mktime(time_tuple) 15 if time_stamp<point: 16 os.remove(os.path.join(cur_path,file_name))
五、把电脑上e盘下面所有的空文件夹删掉
1 import os 2 res =os.walk(r'E:\\') 3 for cur_path, dirs, files in res: 4 if len(dirs) == 0 and len(files) == 0: 5 os.removedirs(cur_path)
六、注册程序
要求账号密码存到数据库里面,存到数据库里面的密码是md5加密的,需要加盐
注册密码要求必须包含大写字母、小写字母、数字最少8位,最长16位
用户名不能重复
自己建用户表,表里的字段有 username、password、failcount、status、failcount默认是0,status默认是正常
import string,pymysql,hashlib name =str(input('请输入用户名:').strip()) pwd = str(input('请输入密码:').strip()) host ='118.24.3.40' user ='jxz' password='123456' db='jxz' port = 3306 charset ='utf8' conn=pymysql.connect(host=host,password=password,user=user,db=db,port=port,charset=charset,autocommit=True) cur =conn.cursor() slect_sql="select count(*) from useInfo_lh where username='%s';"%name cur.execute(slect_sql) if cur.fetchone()[0]: print('该用户名已注册!') elif len(pwd)<8 or len(pwd)>16 or not (set(pwd)&set(string.ascii_uppercase) and set(pwd)&set(string.ascii_lowercase)): print('密码必须为8-16位,且包含大写和小写字母') else: m =hashlib.md5((pwd+'xhz').encode()) new_pwd=m.hexdigest() insert_sql ="insert into useInfo_lh(username,password) value ('%s','%s');"%(name,new_pwd) cur.execute(insert_sql) print('注册成功!') cur.close() conn.close()
七、登录程序
用上面注册成功的用户进行登录,从数据库里面取到账号密码进行登录,每个用户登录失败一次错误次数加1,登录错误次数超过3次,status状态改为锁定,锁定的用户不能登录
import string,random,pymysql,hashlib name =str(input('请输入用户名:').strip()) pwd = str(input('请输入密码:').strip()) m =hashlib.md5((pwd+'xhz').encode()) new_pwd=m.hexdigest() host ='118.24.3.40' user ='jxz' password='123456' db='jxz' port = 3306 charset ='utf8' conn=pymysql.connect(host=host,password=password,user=user,db=db,port=port,charset=charset,autocommit=True) cur =conn.cursor() slect_sql="select * from useInfo_lh where username='%s';"%name #useInfo_lh字段:username、password、failcount、status cur.execute(slect_sql) result=cur.fetchone() if result==None: print('该用户尚未注册!') elif result[3]==0: #status 为0 print('该用户已锁定,不能登录') elif result[1]!=new_pwd: print('密码错误') new_failcount=result[2]+1 #失败次数加1 new_status=1 if new_failcount>3: new_status=0 #改为锁定状态 update_sql="update useInfo_lh set failcount=%d , status= %d where username='%s';"%(new_failcount,new_status,name) cur.execute(update_sql) else: print('登录成功') cur.close() conn.close()
八、python实现随机权重分配:
View Code
传入一个选择字典,选项是key,value是权重,然后按照权重选择一选项
字典格式:{'喝一瓶':30,'喝3瓶':50,'不喝':1,'买单':19}
d = {'喝一瓶':30,'喝3瓶':50,'不喝':1,'买单':19}
# 方法一 import random def choice(d:dict): all_choice=[] #存放所有的选项 for k,v in d.items(): # for i in range(v): # all_choice.append(k) [all_choice.append(k) for i in range(v)] #用列表生成式 res =random.choice(all_choice) return res print(choice({'喝1瓶':30,'喝3瓶':50,'不喝':1,'买单':19})) # 方法二: import random def weight_random_choice(dic:dict): weight_sum = sum(dic.values()) n = random.randint(1,weight_sum) current_weight = 0 for key,weight in dic.items(): current_weight+=weight if current_weight>=n: return key print(weight_random_choice({'喝一瓶':30,'喝3瓶':50,'不喝':1,'买单':19}))
九、把JNZ.xls中的汉字人名转成用户名,写到后面的单元格中
例如:网络-安求凤 : wl_anqiufeng
现场-杨帆 : xc_yangfan
蹭课-张哲: ck_zhangzhe
import xpinyin,xlwt,xlrd,string from xlutils import copy book = xlrd.open_workbook('JNZ.xls') sheet =book.sheet_by_index(0) new_book = copy.copy(book) sheet2 = new_book.get_sheet(0) s = xpinyin.Pinyin() for i in range(sheet.nrows): if i: name1 = sheet.cell(i,0).value name_pinyin=s.get_pinyin(name1,'').replace('wangluo','wl').replace('xianchang','xc').replace('cengke','ck') #将名字中的- -- __ 都替换成 _ for n in name_pinyin: if n not in string.ascii_lowercase: res = name_pinyin.replace(n,'_') xhx_count = res.count('_') #下划线的个数 if xhx_count>1: res = res.replace('_'*xhx_count,'_') #将多个下划线替换成一个 sheet2.write(i,1,res) new_book.save('JNZ.xls')
十、导出数据库中表信息到Excel表中
写一个函数,传入任意一个表名,导出这个表里面所有的数据,字段名是表头,表里面的每行数据是excel的每一行
例如username表里面的字段有id、username、password、addr、phone、email、status,那这几个字段就当做表头,数据就当做每一行的数据
import xlwt,pymysql def export_tableInfo(tablename): book = xlwt.Workbook() sheet = book.add_sheet('sheet1') host = '118.24.3.40' user = 'jxz' password = '123456' db = 'jxz' port = 3306 charset = 'utf8' conn = pymysql.connect(host=host, password=password, user=user, db=db, port=port, charset=charset, autocommit=True) cur = conn.cursor() sql = 'select * from %s ;'%tablename cur.execute(sql) info = cur.description #表头信息 返回的是一个元组(二维数组) datas = cur.fetchall() #表数据 返回的是一个元组(二维数组) # 写入表头信息 count = 0 for i in info: sheet.write(0, count, i[0]) count += 1 # 写入表数据 # r = 1 # for row in datas: # c = 0 # for data in row: # sheet.write(r, c, data) # c += 1 # r += 1 for row,data in enumerate(datas): for col,value in enumerate(data): sheet.write(row+1,col,value) book.save(tablename+'.xls') cur.close() conn.close() export_tableInfo('app_myuser')
十一、一个字符串里面aAd123sdacD12dad2,然后遇到数字取第一个,后面的数字用来分隔,要求结果是这样:[aAd1,sdacD1,dad2]
View Code
1 # 方法一: 2 s ='aAd123sdacD12dad2' 3 s1='' 4 l=[] 5 6 for i in s: 7 s1 = s1+i 8 if i.isdigit(): 9 if not s1.isdigit(): 10 l.append(s1) 11 s1='' 12 print(l) 13 14 15 # 方法二: 用正则表达式 16 import re 17 s = 'aAd123sdacD12dad2' 18 print(re.findall('[A-Za-z]+[0-9]', s))